protocol

package
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package protocol implements the Huawei CodeArts / 码道 cloud protocol: PKCE + DPoP OAuth, STS refresh, SDK-HMAC-SHA256 signing, v2 chat, and model catalogs.

Index

Constants

View Source
const (
	PluginID      = "codearts"
	PluginName    = "CodeArts (华为码道)"
	PluginVersion = "0.1.11"
	PluginAuthor  = "codeartsPlugin"

	// Provider is the CPA auth/executor identifier and auth-file type.
	Provider = "codearts"

	SnapEngineAPIHost = "https://snap-access.cn-north-4.myhuaweicloud.com"
	SnapManagerHost   = SnapEngineAPIHost + "/snap-manager"
	PortalHost        = "https://codearts.huaweicloud.com/portal"
	STSHost           = "https://sts.cn-north-4.myhuaweicloud.com"
	BenefitHost       = "https://opengw.developer.huaweicloud.com"

	ClientID = "codearts-agent"

	EpChatV2         = "/api/v2/chat/completions"
	EpAgentList      = "/v1/agent-center/agents/useragents"
	EpAgentDetail    = "/v1/agent-center/agents/detail"
	EpModelBuiltin   = "/v1/model/builtin"
	EpBenefitConfig  = "/api/v1/gateway/config"
	EpBenefitClaim   = "/api/v1/benefit/claim"
	EpLoginTicket    = "/v1/login/ticket"
	EpOAuthTokens    = "/v1/oauth2/tokens"
	EpCurrentUser    = "/v1/current/user"
	EpCallerIdentity = "/v5/caller-identity"

	OAuthPluginName    = "snap_AIIDE"
	OAuthPluginVersion = "5.2.0"

	HeaderMaasType  = "maas_type"
	HeaderModelID   = "model-id"
	HeaderModelName = "model-name"
	MaasBenefit     = "benefit"

	SigningAlgorithm = "SDK-HMAC-SHA256"
	DefaultChatHost  = "snap-access.cn-north-4.myhuaweicloud.com"
)

Variables

This section is empty.

Functions

func AccountKey

func AccountKey(c Credential) string

AccountKey is the in-process catalog id for this credential. Huawei token responses sometimes omit user_id; fall back to access_key_id so benefit flags from model.for_auth still apply at execute time.

func ApplyBenefitHeaders

func ApplyBenefitHeaders(req *http.Request, benefit bool, modelID string)

ApplyBenefitHeaders sets maas_type / model-id / model-name on req when benefit is true. These headers must be present before SignRequest so they enter SignedHeaders.

func BuildAuthorizeURL

func BuildAuthorizeURL(cfg LoginConfig, ticketID, codeChallenge string, port int) string

BuildAuthorizeURL constructs https://codearts.huaweicloud.com/portal/authorize?...

func CanonicalHeaders

func CanonicalHeaders(req *http.Request) (headers, signed string)

CanonicalHeaders returns the signed header block (lowercase keys, sorted) and the SignedHeaders list. All request headers participate.

func CanonicalModel

func CanonicalModel(id string) string

CanonicalModel maps case variants to the ID last seen in discovery.

func CanonicalQuery

func CanonicalQuery(raw string) string

CanonicalQuery sorts query parameters.

func CanonicalRequest

func CanonicalRequest(method, canonicalURI, canonicalQuery, canonicalHeaders, signedHeaders, payloadHash string) string

CanonicalRequest is the Huawei SDK canonical request string.

func CanonicalURI

func CanonicalURI(path string) string

CanonicalURI percent-encodes each path segment and always ends with "/".

func ChatTarget

func ChatTarget(snapBase string) string

ChatTarget is the upstream chat-completions URL.

func DoJSON

func DoJSON(client *http.Client, req *http.Request, maxBody int64) (status int, body []byte, err error)

DoJSON performs req with client and reads at most maxBody bytes.

func ExtractCallbackCode

func ExtractCallbackCode(raw string) string

ExtractCallbackCode pulls an OAuth code from a pasted callback URL or raw code.

func ExtractCallbackRedirect

func ExtractCallbackRedirect(raw string) string

ExtractCallbackRedirect pulls the Huawei continue-login URL from a first-hop callback.

func ExtractCallbackSecret

func ExtractCallbackSecret(raw string) string

ExtractCallbackSecret pulls portal-issued secret from a callback URL.

func FileNameFor

func FileNameFor(c Credential) string

FileNameFor returns the host auth file name for this credential. User id wins when set. Otherwise the access key is used so accounts that omit user_id do not share one file. The access key is not prefixed with ak:; that form belongs only to AccountKey.

func HMACHex

func HMACHex(key, msg string) string

HMACHex returns lowercase hex HMAC-SHA256(key, msg).

func IsBenefitModel

func IsBenefitModel(accountID, model string) bool

IsBenefitModel reports whether this account+model must send maas_type=benefit.

func LooksLikeCodeArts

func LooksLikeCodeArts(raw []byte, fileName string) bool

LooksLikeCodeArts reports whether raw JSON is a CodeArts auth file. Type is read from the raw object. ParseCredential still defaults an empty type for credentials this plugin already owns; that default must not claim a file whose type is missing or blank.

func MarshalCredential

func MarshalCredential(c Credential) ([]byte, error)

MarshalCredential encodes the credential as JSON.

func MergeCredential added in v0.1.2

func MergeCredential(original []byte, c Credential) ([]byte, error)

MergeCredential overlays c onto the JSON object in original and returns the result. Keys this plugin does not own (CPA's prefix, priority, proxy_url, note, disabled, ...) are kept so a parse or refresh write does not drop them. An empty or non-object original yields MarshalCredential(c).

func ModelMaxTokens added in v0.1.8

func ModelMaxTokens(accountID, model string) int64

ModelMaxTokens is the discovered maximum output for this account and model. Zero means the catalog has no limit, so the caller must omit max_tokens.

func NewChatRequest

func NewChatRequest(target string, body []byte, cred SignCredential, model string, benefit, stream bool, opts SignOptions) (*http.Request, error)

NewChatRequest builds a signed POST to /api/v2/chat/completions.

func NewTicketRequest

func NewTicketRequest(cfg LoginConfig, ticketID, secret string) (*http.Request, error)

NewTicketRequest builds GET snap-manager /v1/login/ticket.

func NewTokenRequest

func NewTokenRequest(cfg LoginConfig, form url.Values, dpop DPoPPrivateJWK) (*http.Request, error)

NewTokenRequest builds a POST to STS with form body and DPoP proof.

func NormalizeNonStreamBody added in v0.1.4

func NormalizeNonStreamBody(body []byte, model string) ([]byte, error)

NormalizeNonStreamBody returns one OpenAI chat completion for a non-stream executor payload. Plain JSON is returned unchanged. SSE is aggregated.

func PKCE

func PKCE() (verifier, challenge string, err error)

PKCE returns a S256 code_verifier and code_challenge.

func ParamInvalid added in v0.1.5

func ParamInvalid(msg string) bool

ParamInvalid reports InferHub.001001005, a client request-shape rejection. Retrying the same body with benefit headers cannot fix it.

func ParseSignature

func ParseSignature(authorization string) string

ParseSignature extracts the Signature hex from an Authorization value.

func ParseSignedHeaders

func ParseSignedHeaders(authorization string) string

ParseSignedHeaders extracts the SignedHeaders list from an Authorization value.

func PostChatCompletions

func PostChatCompletions(client *http.Client, target string, body []byte, cred SignCredential, model string, benefit, stream bool, opts SignOptions) (*http.Response, error)

PostChatCompletions signs and sends the OpenAI-shaped body to the v2 endpoint.

func PrepareChatBody

func PrepareChatBody(raw []byte, model string, stream bool, maxOutput int) ([]byte, string, error)

PrepareChatBody rebuilds an OpenAI chat body into the shape InferHub accepts. Unknown fields are dropped. A named tool_choice object becomes the string "required" with tools reduced to that one function: InferHub rejects the object form with InferHub.001001005.400.

func RandomHex

func RandomHex(n int) (string, error)

RandomHex returns n random bytes as lowercase hex (length 2n).

func RandomHexOrTime

func RandomHexOrTime(n int) string

RandomHexOrTime returns n random bytes as hex, falling back to a timestamp.

func ReadAllLimited

func ReadAllLimited(r io.Reader, n int64) ([]byte, error)

ReadAllLimited reads at most n bytes from r.

func RedirectURI

func RedirectURI(cfg LoginConfig, port int) string

RedirectURI is the loopback URI Huawei binds to the authorization code.

func SHA256Hex

func SHA256Hex(b []byte) string

SHA256Hex returns the lowercase hex SHA-256 of b.

func SafePortalRedirect

func SafePortalRedirect(raw string) string

SafePortalRedirect returns raw if it is an https Huawei portal/login URL.

func SetAccountModels

func SetAccountModels(accountID string, infos []ModelInfo)

SetAccountModels replaces one account's catalog.

func SignDPoPProof

func SignDPoPProof(jwk DPoPPrivateJWK, htu string) (string, error)

SignDPoPProof builds an ES256 DPoP JWT (htm=POST, htu=token endpoint).

func SignRequest

func SignRequest(req *http.Request, body []byte, cred SignCredential, opts SignOptions)

SignRequest adds X-Sdk-Date, X-Security-Token, X-Sdk-Content-Sha256, Host, and Authorization (SDK-HMAC-SHA256). Every header on req except Authorization is signed. CanonicalURI always ends with "/".

func StringToSign

func StringToSign(xDate, canonicalRequest string) string

StringToSign is algorithm + date + hex(sha256(canonicalRequest)).

func StripModelPrefix added in v0.1.2

func StripModelPrefix(model, prefix string) string

StripModelPrefix returns the Huawei model id for a CPA route name. CPA namespaces an auth's models as "<prefix>/<id>" when the auth file sets prefix. Huawei only accepts the bare id, so a leading "<prefix>/" is removed. When prefix is unknown, a single leading "<seg>/" is still removed: Huawei ids themselves never contain "/", and the in-process catalog is empty until model.for_auth has run. A name with more than one slash is left as-is.

func TicketURL

func TicketURL(cfg LoginConfig, ticketID, secret string) string

TicketURL is the snap-manager ticket poll URL.

func TokenEndpoint

func TokenEndpoint(cfg LoginConfig) string

TokenEndpoint is the STS oauth2/tokens URL.

func TokenFormAuthorizationCode

func TokenFormAuthorizationCode(cfg LoginConfig, code, codeVerifier string, port int) url.Values

TokenFormAuthorizationCode is the STS form for grant_type=authorization_code.

func TokenFormRefresh

func TokenFormRefresh(cfg LoginConfig, refreshToken, codeVerifier string) url.Values

TokenFormRefresh is the STS form for grant_type=refresh_token.

func TranslateStreamChunk added in v0.1.4

func TranslateStreamChunk(chunk []byte, model string) (payloads [][]byte, done bool, err error)

TranslateStreamChunk converts one upstream read into JSON objects for host.stream.emit. The caller must not add a "data:" prefix. done is true when the upstream sent the SSE terminator or the read was a finished JSON object. An upstream error_code returns an error instead of a chunk.

func UpstreamChatError

func UpstreamChatError(status int, body []byte) string

UpstreamChatError returns a non-empty message when Huawei wrapped a failure in a 2xx JSON body (e.g. error_code 4004 benefit not found).

Types

type CallbackParts

type CallbackParts struct {
	Code     string
	Secret   string
	Redirect string
	State    string
	TicketID string
}

CallbackParts is the Huawei loopback callback: first hop is secret+redirect, second hop carries the authorization code. State and TicketID are optional binding keys; the authorize URL does not send state.

func ParseCallback

func ParseCallback(raw string) CallbackParts

ParseCallback extracts code / secret / redirect / state / ticket_id from a pasted callback URL, a labeled Chinese prompt, or a raw authorization code.

type Credential

type Credential struct {
	Type            string            `json:"type"`
	UserID          string            `json:"user_id,omitempty"`
	UserName        string            `json:"user_name,omitempty"`
	DomainID        string            `json:"domain_id,omitempty"`
	AccessKeyID     string            `json:"access_key_id"`
	SecretAccessKey string            `json:"secret_access_key"`
	SecurityToken   string            `json:"security_token"`
	Expiration      string            `json:"expiration,omitempty"`
	RefreshToken    string            `json:"refresh_token"`
	CodeVerifier    string            `json:"code_verifier,omitempty"`
	ClientID        string            `json:"client_id,omitempty"`
	DPoPPrivateKey  map[string]string `json:"dpop_private_key,omitempty"`
	// CPA unmarshals updated_at as time.Time, so a unix number makes the auth
	// file unreadable and the model list empty. Accept the old number on read.
	UpdatedAt flexTime `json:"updated_at,omitempty"`
}

Credential is the persisted CodeArts OAuth + STS record. client_id and dpop_private_key.d must survive refresh; refresh_token is one-time.

func ApplyRefresh

func ApplyRefresh(prev Credential, tok TokenResponse) Credential

ApplyRefresh copies rotated STS + refresh_token onto prev while keeping client_id, code_verifier, and the DPoP private JWK (including d) unchanged.

func NewCredentialFromToken

func NewCredentialFromToken(tok TokenResponse, verifier string, clientID string, dpop DPoPPrivateJWK) Credential

NewCredentialFromToken builds a persistable credential from a token response.

func ParseCredential

func ParseCredential(raw []byte) (Credential, error)

ParseCredential decodes a persisted auth JSON object.

type DPoPPrivateJWK

type DPoPPrivateJWK map[string]string

DPoPPrivateJWK is the P-256 private JWK persisted with the refresh_token.

func NewDPoPPrivateJWK

func NewDPoPPrivateJWK() (DPoPPrivateJWK, error)

NewDPoPPrivateJWK generates a persistable ES256 P-256 private JWK.

type LegacyCreds

type LegacyCreds struct {
	Access        string `json:"access"`
	Secret        string `json:"secret"`
	SecurityToken string `json:"securitytoken"`
	ExpiresAt     string `json:"expires_at"`
}

LegacyCreds is the ticket-channel credential object.

type LoginConfig

type LoginConfig struct {
	ClientID      string
	PortalHost    string
	SnapManager   string
	STSHost       string
	RedirectPath  string
	PluginName    string
	PluginVersion string
}

LoginConfig is the Huawei OAuth/PKCE configuration.

func DefaultLoginConfig

func DefaultLoginConfig() LoginConfig

DefaultLoginConfig matches the official CodeArts Agent plugin.

type ModelInfo

type ModelInfo struct {
	ID            string `json:"id"`
	Name          string `json:"name,omitempty"`
	ContextWindow int64  `json:"contextWindow,omitempty"`
	MaxTokens     int64  `json:"maxTokens,omitempty"`
	Benefit       bool   `json:"benefit,omitempty"`
	Desc          string `json:"desc,omitempty"`
}

ModelInfo is a discovered model.

func AccountModels

func AccountModels(accountID string) ([]ModelInfo, bool)

AccountModels returns a copy of one account catalog.

func DiscoverModels

func DiscoverModels(client *http.Client, cred SignCredential, accountID string, snapBase, benefitBase string, claimBenefit bool) []ModelInfo

DiscoverModels fetches agent-center + builtin + benefit catalogs. Failures on individual sources are ignored; an empty merge stays empty.

func MergeModels

func MergeModels(sets ...[]ModelInfo) []ModelInfo

MergeModels de-duplicates by lower(id); benefit is OR-ed.

type STSCreds

type STSCreds struct {
	AccessKeyID     string `json:"access_key_id"`
	SecretAccessKey string `json:"secret_access_key"`
	SecurityToken   string `json:"security_token"`
	Expiration      string `json:"expiration"`
}

STSCreds is the nested credentials object from oauth2/tokens.

type SignCredential

type SignCredential struct {
	AccessKeyID     string
	SecretAccessKey string
	SecurityToken   string
}

SignCredential is the STS (or permanent) AK/SK used for SDK-HMAC-SHA256.

func SignCredentialFrom

func SignCredentialFrom(c Credential) SignCredential

SignCredentialFrom returns HMAC material.

type SignOptions

type SignOptions struct {
	// Date, if non-zero, is used as X-Sdk-Date instead of time.Now.
	Date time.Time
}

SignOptions controls deterministic signing for tests.

type TokenResponse

type TokenResponse struct {
	UserID       string      `json:"user_id"`
	UserName     string      `json:"user_name"`
	DomainID     string      `json:"domain_id"`
	RefreshToken string      `json:"refresh_token"`
	Credentials  STSCreds    `json:"credentials"`
	Credential   LegacyCreds `json:"credential"`
	Error        string      `json:"error"`
	ErrorCode    string      `json:"error_code"`
	ErrorMessage string      `json:"error_msg"`
}

TokenResponse is the STS / oauth2/tokens JSON body.

func ParseTokenResponse

func ParseTokenResponse(raw []byte) (TokenResponse, error)

ParseTokenResponse decodes an oauth2/tokens or ticket JSON body.

func (TokenResponse) HasSTS

func (t TokenResponse) HasSTS() bool

HasSTS reports whether the response contains usable STS material.

func (*TokenResponse) Normalize

func (t *TokenResponse) Normalize()

Normalize fills credentials from the legacy ticket object when needed.

Jump to

Keyboard shortcuts

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