jumpserver

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2026 License: MIT Imports: 35 Imported by: 0

README

CN EN

jumpserver-sdk-go

Go SDK for JumpServer REST API, targeting v4.10.x.

中文文档 | English

Go Reference Go Report Card

Features

  • Full CRUD coverage — 28 service modules covering users, assets, accounts, permissions, audits, tickets, ops jobs, and more
  • Typed asset categories — Hosts, Devices, Databases, Webs, Clouds, Customs each with dedicated CRUD operations
  • Multiple auth methods — AccessKey (HMAC-SHA256), Bearer Token, Private Token, HTTP Basic, custom Authenticator
  • Organization scopeWithOrgScope(id) switches org context without rebuilding the client
  • Auto paginationWalkPages() iterates through all pages automatically
  • Smart retry — Exponential backoff with full jitter, retries only transient errors (timeout, connection reset, 429/5xx)
  • Zero third-party dependencies — pure standard library
  • Go 1.25 — uses math/rand/v2, maps.Clone, for range int, and other modern features

Installation

go get github.com/fit2cloud-sdk/jumpserver-sdk-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    jumpserver "github.com/fit2cloud-sdk/jumpserver-sdk-go"
    "github.com/fit2cloud-sdk/jumpserver-sdk-go/model"
)

func main() {
    client := jumpserver.NewClient(
        jumpserver.WithBaseURL(os.Getenv("JUMPSERVER_URL")),
        jumpserver.WithAccessKeyAuth(
            os.Getenv("JUMPSERVER_KEY_ID"),
            os.Getenv("JUMPSERVER_SECRET_ID"),
        ),
    )

    ctx := context.Background()

    // List users
    users, _, err := client.Users.List(ctx, nil, &jumpserver.ListOptions{Limit: 20})
    if err != nil {
        log.Fatal(err)
    }
    for _, u := range users {
        fmt.Println(u.Username, u.Email)
    }

    // Filter by condition
    users, _, _ = client.Users.List(ctx,
        map[string]string{"username": "admin"},
        &jumpserver.ListOptions{Limit: 10},
    )

    // Create a host asset
    host, _, _ := client.Hosts.Create(ctx, &model.AssetRequest{
        Name:      "web-01",
        Address:   "192.168.1.10",
        Platform:  1, // Linux platform ID
        Protocols: []model.NamePort{{Name: "ssh", Port: 22}},
    })
    fmt.Println("Created:", host.ID)
}

Authentication

// AccessKey HMAC-SHA256 signature (recommended for service accounts)
jumpserver.WithAccessKeyAuth(keyID, secretID)

// Bearer Token
jumpserver.WithBearerToken(token)

// Private Token (Authorization: Token <token>)
jumpserver.WithPrivateToken(token)

// HTTP Basic
jumpserver.WithBasicAuth(username, password)

// Custom authenticator
jumpserver.WithAuthenticator(myAuth)

Organization Scope

JumpServer routes most endpoints through organizations. The default header is X-JMS-ORG: ROOT.

// Set default organization
client := jumpserver.NewClient(
    jumpserver.WithBaseURL(url),
    jumpserver.WithOrg("org-uuid"),
    // ...
)

// Derive a scoped client (shares underlying HTTP connection)
scoped := client.WithOrgScope("other-org-uuid")
users, _, _ := scoped.Users.List(ctx, nil, nil)

Pagination

// Manual pagination
users, resp, _ := client.Users.List(ctx, nil, &jumpserver.ListOptions{
    Limit:  20,
    Offset: 0,
    Search: "admin",
})
if resp.HasNextPage() {
    // fetch next page...
}

// Auto-iterate all pages
var all []model.User
jumpserver.WalkPages(ctx, &jumpserver.ListOptions{Limit: 100}, 0,
    func(ctx context.Context, opts *jumpserver.ListOptions) (*jumpserver.Response, error) {
        users, resp, err := client.Users.List(ctx, nil, opts)
        if err != nil { return resp, err }
        all = append(all, users...)
        return resp, nil
    },
)

Error Handling

user, _, err := client.Users.Get(ctx, id)
if err != nil {
    if jumpserver.IsNotFound(err) {
        fmt.Println("user not found")
    }
    if jumpserver.IsUnauthorized(err) {
        fmt.Println("auth failed")
    }
    if jumpserver.IsRateLimited(err) {
        fmt.Println("rate limited")
    }

    var apiErr *jumpserver.APIError
    if errors.As(err, &apiErr) {
        fmt.Println(apiErr.StatusCode, apiErr.Message, string(apiErr.Body))
    }
}

Retry

Default: 3 retries with exponential backoff and full jitter, respects Retry-After header:

client := jumpserver.NewClient(
    jumpserver.WithBaseURL(url),
    jumpserver.WithRetry(5, 200*time.Millisecond, 30*time.Second),
    // ...
)

Retried:

  • HTTP 408, 429, 500, 502, 503, 504
  • Transient network errors (timeout, connection reset, temporary DNS failure)

Not retried:

  • context.Canceled / context.DeadlineExceeded
  • TLS certificate errors
  • 4xx client errors (except 408, 429)

Services

Service Field Description
Auth client.Auth Login, MFA, connection tokens, SSO
Users client.Users User CRUD, Profile
User Groups client.UserGroups Group CRUD, member management
Roles client.Roles Org/system role queries
Assets (generic) client.Assets Generic asset queries, permission users
Hosts client.Hosts Host CRUD
Devices client.Devices Network device CRUD
Databases client.Databases Database CRUD
Webs client.Webs Web asset CRUD
Clouds client.Clouds Cloud asset CRUD
Customs client.Customs Custom asset CRUD
Nodes client.Nodes Asset tree node CRUD
Platforms client.Platforms Platform template queries
Zones client.Zones Network zone CRUD
Gateways client.Gateways Gateway CRUD
Labels client.Labels Label CRUD
Accounts client.Accounts Account CRUD, connectivity tests
Account Templates client.AccountTemplates Account template CRUD
Change Secrets client.ChangeSecrets Secret rotation policy CRUD + execute
Account Backups client.AccountBackups Backup plan CRUD + execute
Organizations client.Organizations Organization CRUD
Permissions client.Permissions Asset permission CRUD, batch-relation add
Self client.Self Current user's own assets & accounts
Command Filters client.CommandFilters Command filter + command group CRUD
Login ACL client.LoginACLs Login ACL queries
Audits client.Audits Sessions, commands, FTP, login & operation logs
Terminal client.Terminal Terminal config, connect methods
Tickets client.Tickets Ticket + workflow management
Settings client.Settings System setting queries
Ops client.Ops Quick-command job create & result query
Enterprise client.Xpack License queries

Package Structure

jumpserver-sdk-go/
├── client.go              # Client, HTTPClient interface
├── auth.go                # Authenticator implementations
├── options.go             # Functional options
├── errors.go              # APIError, error helpers
├── pagination.go          # ListOptions, Response, WalkPages
├── version.go             # SDK version
├── client_test.go         # Unit tests
├── Makefile               # Build/test/coverage commands
│
├── internal/core/         # Shared types (HTTPClient interface)
├── internal/sdkutil/      # Internal utilities
├── model/                 # Data models (pure type definitions)
│
├── auth/                  # Authentication service
├── users/                 # Users & groups (users.go, groups.go)
├── rbac/                  # Roles
├── assets/                # Assets/nodes/platforms/zones/gateways (7 files)
├── accounts/              # Accounts/templates/backup/change-secret (4 files)
├── orgs/                  # Organizations
├── perms/                 # Permissions (+ self assets)
├── ops/                   # Ops jobs
├── acls/                  # Command filters & login ACLs
├── audits/                # Audit logs (sessions, commands, ftplogs, logs)
├── terminal/              # Terminal
├── tickets/               # Tickets
├── settings/              # Settings
├── xpack/                 # Enterprise
├── labels/                # Labels
│
└── examples/
    ├── integration/       # Full CRUD integration test (200+ items)
    ├── list-users/
    ├── create-asset/
    └── connection-token/  # Connection token full flow

Integration Test

Run the full CRUD test suite against a real JumpServer instance:

export JUMPSERVER_URL=https://your-jumpserver.example.com
export JUMPSERVER_KEY_ID=your-key-id
export JUMPSERVER_SECRET_ID=your-secret-id

make integration
# or directly
go run ./examples/integration

Development

make build       # Build all packages
make test        # Run unit tests
make vet         # Static analysis
make all         # vet + test + build
make coverage    # Generate test coverage report
make clean       # Clean build artifacts

Unit Test

go test ./...

License

MIT — see LICENSE.

Documentation

Index

Constants

View Source
const Version = "0.2.0"

Version is the semantic version of the SDK. Bump whenever the public API surface changes in a user-visible way.

Variables

View Source
var (
	ErrBadRequest   = &APIError{StatusCode: http.StatusBadRequest}
	ErrUnauthorized = &APIError{StatusCode: http.StatusUnauthorized}
	ErrForbidden    = &APIError{StatusCode: http.StatusForbidden}
	ErrNotFound     = &APIError{StatusCode: http.StatusNotFound}
	ErrConflict     = &APIError{StatusCode: http.StatusConflict}
	ErrRateLimited  = &APIError{StatusCode: http.StatusTooManyRequests}
	ErrServer       = &APIError{StatusCode: http.StatusInternalServerError}
)

Sentinel errors for common status classes.

Functions

func IsForbidden

func IsForbidden(err error) bool

func IsNotFound

func IsNotFound(err error) bool

func IsRateLimited

func IsRateLimited(err error) bool

func IsUnauthorized

func IsUnauthorized(err error) bool

func WalkPages

func WalkPages(ctx context.Context, initial *ListOptions, maxPages int, fetch PageFetcher) error

WalkPages repeatedly invokes fetch with an advancing ListOptions until no next page is reported. maxPages bounds the total number of HTTP calls as a safety valve; pass 0 for "unbounded".

Types

type APIError

type APIError struct {
	StatusCode int
	Method     string
	URL        string
	Body       []byte
	Message    string
	Response   *http.Response
}

APIError represents a non-2xx response from the JumpServer API.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether target is an *APIError with the same status code.

type Authenticator

type Authenticator interface {
	// Authenticate mutates req in place (typically by setting headers
	// or cookies). Returning a non-nil error aborts the request.
	Authenticate(req *http.Request) error
}

Authenticator signs or annotates an outgoing *http.Request with credentials. Implementations must be safe for concurrent use.

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth sets HTTP Basic credentials on the request.

func (*BasicAuth) Authenticate

func (a *BasicAuth) Authenticate(req *http.Request) error

Authenticate implements Authenticator.

type BearerTokenAuth

type BearerTokenAuth struct {
	Token string
}

BearerTokenAuth sets "Authorization: Bearer <token>".

func (*BearerTokenAuth) Authenticate

func (a *BearerTokenAuth) Authenticate(req *http.Request) error

Authenticate implements Authenticator.

type Client

type Client struct {
	Auth             *auth.Service
	Users            *users.Service
	UserGroups       *users.GroupsService
	Roles            *rbac.Service
	Assets           *assets.AssetsService
	Hosts            *assets.CategoryService
	Devices          *assets.CategoryService
	Databases        *assets.CategoryService
	Webs             *assets.CategoryService
	Clouds           *assets.CategoryService
	Customs          *assets.CategoryService
	Nodes            *assets.NodesService
	Platforms        *assets.PlatformsService
	Zones            *assets.ZonesService
	Gateways         *assets.GatewaysService
	Labels           *labels.Service
	Accounts         *accounts.Service
	AccountTemplates *accounts.TemplatesService
	ChangeSecrets    *accounts.ChangeSecretService
	AccountBackups   *accounts.BackupService
	Organizations    *orgs.Service
	Permissions      *perms.Service
	Self             *perms.SelfService
	CommandFilters   *acls.CommandFiltersService
	LoginACLs        *acls.LoginACLsService
	Audits           *audits.Service
	Terminal         *terminal.Service
	Tickets          *tickets.Service
	Settings         *settings.Service
	Ops              *ops.Service
	Xpack            *xpack.Service
	// contains filtered or unexported fields
}

Client talks to a JumpServer instance. Construct one with NewClient.

func NewClient

func NewClient(opts ...Option) *Client

NewClient returns a ready-to-use Client.

func (*Client) BaseURL

func (c *Client) BaseURL() *url.URL

BaseURL returns the configured base URL.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*Response, error)

Do sends req and decodes the response into v. When v is a *bytes.Buffer the raw body is copied into it instead.

func (*Client) DoRaw

func (c *Client) DoRaw(ctx context.Context, req *http.Request, w io.Writer) (*Response, error)

DoRaw sends req and streams the response body into w without JSON decoding. Use it for binary downloads (e.g. session replays, files).

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, body any) (*http.Request, error)

NewRequest builds an *http.Request against the client's base URL. Body is JSON-encoded when non-nil.

func (*Client) WithOrgScope

func (c *Client) WithOrgScope(id string) *Client

WithOrgScope returns a copy of c whose default X-JMS-ORG header is overridden to id.

type HTTPClient

type HTTPClient = core.HTTPClient

HTTPClient is the interface that service sub-packages use to make HTTP requests. *Client satisfies this interface.

type ListOptions

type ListOptions = core.ListOptions

ListOptions configures pagination and search for list endpoints.

type Logger

type Logger interface {
	Printf(format string, v ...any)
}

Logger is a minimal interface satisfied by *log.Logger. Pass any compatible implementation to WithLogger.

type Option

type Option func(*clientConfig)

Option configures a Client. Pass any number of options to NewClient.

func WithAccessKeyAuth

func WithAccessKeyAuth(keyID, secretID string) Option

WithAccessKeyAuth authenticates using HMAC-SHA256 HTTP Signature (JumpServer "Access Key"). This is the recommended way to talk to the API with a service account.

func WithAuthenticator

func WithAuthenticator(a Authenticator) Option

WithAuthenticator installs a fully custom Authenticator.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL sets the JumpServer base URL, e.g. "https://jumpserver.example.com". Trailing slashes are trimmed.

func WithBasicAuth

func WithBasicAuth(username, password string) Option

WithBasicAuth authenticates with HTTP Basic. Useful to obtain a Bearer token through the authentication endpoint.

func WithBearerToken

func WithBearerToken(token string) Option

WithBearerToken authenticates with "Authorization: Bearer <token>".

func WithCookie

func WithCookie(name, value string) Option

WithCookie adds a cookie sent on every request.

func WithDebugRequests

func WithDebugRequests(on bool) Option

WithDebugRequests toggles verbose request/response dumps in the logger output.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient replaces the default *http.Client. When set, the timeout/retry/InsecureSkipVerify options are still respected for retry logic but the caller owns the transport.

func WithHeader

func WithHeader(key, value string) Option

WithHeader adds an extra header sent on every request.

func WithInsecureSkipVerify

func WithInsecureSkipVerify(skip bool) Option

WithInsecureSkipVerify controls TLS certificate verification. The default is true for compatibility with self-signed JumpServer deployments, but production code should set this to false.

func WithLogger

func WithLogger(l Logger) Option

WithLogger enables request/response logging via the supplied Logger.

func WithOrg

func WithOrg(id string) Option

WithOrg sets the default X-JMS-ORG header value. JumpServer routes most endpoints through an organization; use "ROOT" (default) for the default organization, "00000000-0000-0000-0000-000000000002" for the global org, or a specific org ID.

func WithPrivateToken

func WithPrivateToken(token string) Option

WithPrivateToken authenticates with "Authorization: Token <token>", the legacy JumpServer private-token scheme.

func WithRetry

func WithRetry(maxRetries int, minWait, maxWait time.Duration) Option

WithRetry configures automatic retries. Retries occur on:

  • HTTP 408, 429, 500, 502, 503, 504 responses
  • Transient network errors (timeout, connection reset, DNS temporary failure)

Permanent errors (TLS failures, context cancellation) are never retried. Backoff uses exponential delay with full jitter, honouring Retry-After headers.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the default User-Agent header.

type PageFetcher

type PageFetcher = core.PageFetcher

PageFetcher paginates through all pages of a list endpoint.

type PrivateTokenAuth

type PrivateTokenAuth struct {
	Token string
}

PrivateTokenAuth sets "Authorization: Token <token>".

func (*PrivateTokenAuth) Authenticate

func (a *PrivateTokenAuth) Authenticate(req *http.Request) error

Authenticate implements Authenticator.

type Response

type Response = core.Response

Response is the typed wrapper returned by every service call.

type SignatureAuth

type SignatureAuth struct {
	KeyID    string
	SecretID string
}

SignatureAuth signs requests with HMAC-SHA256 using the JumpServer "Access Key" scheme, which is a profile of the IETF HTTP Signatures draft. The signed headers are "(request-target)" and "date".

func (*SignatureAuth) Authenticate

func (a *SignatureAuth) Authenticate(req *http.Request) error

Authenticate implements Authenticator.

Directories

Path Synopsis
examples
connection-token command
Connection token flow example — mirrors the Python UserClient workflow.
Connection token flow example — mirrors the Python UserClient workflow.
create-asset command
Example: create a host asset and bind it to a node.
Example: create a host asset and bind it to a node.
integration command
Integration test: full CRUD lifecycle for every JumpServer v4 service.
Integration test: full CRUD lifecycle for every JumpServer v4 service.
list-users command
Example: list users from a JumpServer instance using an AccessKey.
Example: list users from a JumpServer instance using an AccessKey.
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL