http

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2025 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Overview

Copyright 2025 Comcast Cable Communications Management, LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

SPDX-License-Identifier: Apache-2.0

Index

Constants

View Source
const (
	AUTHORIZATION = "Authorization"
	AUTH_TOKEN    = "token"
	AUTH_SUBJECT  = "X-Auth-Subject"
	UNKNOWN_USER  = "UNKNOWN_USER"
	RequestID     = "X-Request-ID"
	KeysURL       = "/v2/sign-keys"
)
View Source
const (
	GetGroupsMembers = "%s/v2/ft/%s"
	GetAllGroups     = "%s/v2/ft"
)
View Source
const (
	Accept                    = "Content-Type"
	ContentType               = "Content-Type"
	ApplicationProtobufHeader = "application/x-protobuf"
	TtlHeader                 = "Xttl"
	OneYearTtl                = "31536000"

	AddGroupMember    = "%s/v2/ft/%s"
	RemoveGroupMember = "%s/v2/ft/%s?field=%s"
)
View Source
const (
	HttpGet    = "GET"
	HttpPost   = "POST"
	HttpDelete = "DELETE"
)
View Source
const (
	OkResponseTemplate = `{"status":200,"message":"OK","data":%v}`

	// TODO, this should be retired
	TR181ResponseTemplate = `{"parameters":%v,"version":"%v"}`
	TYPE_409              = "EntityConflictException"
	TYPE_400              = "ValidationRuntimeException"
	TYPE_404              = "EntityNotFoundException"
	TYPE_500              = "InternalServerErrorException"
	TYPE_501              = "NotImplementedException"
	TYPE_415              = "UnsupportedMediaTypeException"
)
View Source
const (
	LevelWarn = iota
	LevelInfo
	LevelDebug
	MetricsEnabledDefault = true

	DEV_PROFILE = "dev"
)
View Source
const (
	PostPrecookPathTemplate = "%s/api/v1/precook/rfc"
)

Variables

View Source
var (
	WebConfServer              *WebconfigServer
	DistributedLockTableTTL    int
	DistributedLockTableRowTTL int
)
View Source
var ErrNoKIDParameter = errors.New("jwt header missing valid \"kid\" parameter")

ErrNoKIDParameter indicates that the provided JWT is missing the "kid" parameter

Functions

func AdminError

func AdminError(w http.ResponseWriter, err error)

func AppName

func AppName() string

AppName is just a convenience func that returns the AppName, used in metrics

func ContextTypeHeader

func ContextTypeHeader(r *http.Request) string

func CreateContentDispositionHeader

func CreateContentDispositionHeader(fileName string) map[string]string

func CreateNumberOfItemsHttpHeaders

func CreateNumberOfItemsHttpHeaders(size int) map[string]string

func Error

func Error(w http.ResponseWriter, err error)

func GetCapabilitiesFromContext

func GetCapabilitiesFromContext(r *http.Request) []string

func GetPermissionsFromContext

func GetPermissionsFromContext(r *http.Request) []string

func IsDevProfile

func IsDevProfile() bool

func LogError

func LogError(w http.ResponseWriter, err error)

func NewAuthTokenCookie

func NewAuthTokenCookie(token string) *http.Cookie

func NewErasedAuthTokenCookie

func NewErasedAuthTokenCookie() *http.Cookie

func NewTlsConfig

func NewTlsConfig(conf *configuration.Config) (*tls.Config, error)

func ReturnJsonResponse

func ReturnJsonResponse(res interface{}, r *http.Request) ([]byte, error)

ReturnJsonResponse - return JSON response to api

func WriteAdminErrorResponse

func WriteAdminErrorResponse(w http.ResponseWriter, status int, errMsg string)

helper function to write a failure json response matching xconf java admin response

func WriteContentTypeAndResponse

func WriteContentTypeAndResponse(w http.ResponseWriter, r *http.Request, rbytes []byte, version string, contentType string)

this is used to return default tr-181 payload while the cpe is not in the db

func WriteErrorResponse

func WriteErrorResponse(w http.ResponseWriter, status int, err error)

helper function to write a failure json response into ResponseWriter

func WriteOkResponse

func WriteOkResponse(w http.ResponseWriter, r *http.Request, data interface{})

helper function to write a json response into ResponseWriter

func WriteOkResponseByTemplate

func WriteOkResponseByTemplate(w http.ResponseWriter, r *http.Request, dataStr string)

func WriteResponseBytes

func WriteResponseBytes(w http.ResponseWriter, rbytes []byte, statusCode int, vargs ...string)

func WriteTR181Response

func WriteTR181Response(w http.ResponseWriter, r *http.Request, params string, version string)

func WriteXconfErrorResponse

func WriteXconfErrorResponse(w http.ResponseWriter, err error)

func WriteXconfResponse

func WriteXconfResponse(w http.ResponseWriter, status int, data []byte)

func WriteXconfResponseAsText

func WriteXconfResponseAsText(w http.ResponseWriter, status int, data []byte)

func WriteXconfResponseHtmlWithHeaders

func WriteXconfResponseHtmlWithHeaders(w http.ResponseWriter, headers map[string]string, status int, data []byte)

func WriteXconfResponseWithHeaders

func WriteXconfResponseWithHeaders(w http.ResponseWriter, headers map[string]string, status int, data []byte)

Types

type AllowedResources

type AllowedResources struct {
	AllowedPartners          []string `json:"allowedPartners,omitempty"`
	AllowedServiceAccountIDs []string `json:"allowedServiceAccountIds,omitempty"`
	AllowedDeviceIDs         []string `json:"allowedDeviceIds,omitempty"`
	AllowedUserIDs           []string `json:"allowedUserIds,omitempty"`
	AllowedTNs               []string `json:"allowedTNs,omitempty"`
}

AllowedResources represents resources defined in the SAT

type AppMetrics

type AppMetrics struct {
	// contains filtered or unexported fields
}

AppMetrics just collects all the needed metrics

func NewMetrics

func NewMetrics() *AppMetrics

NewMetrics creates all the metrics needed for xconfadmin

func (*AppMetrics) MetricsHandler

func (m *AppMetrics) MetricsHandler(next http.Handler) http.Handler

func (*AppMetrics) UpdateAPIMetrics

func (s *AppMetrics) UpdateAPIMetrics(r *http.Request, status int, startTime time.Time)

updateMetrics updates api_req_total, number of API calls

func (*AppMetrics) UpdateExternalAPIMetrics

func (s *AppMetrics) UpdateExternalAPIMetrics(service string, method string, statusCode int, startTime time.Time)

updateExternalAPIMetrics updates duration and counts for external API calls to titan, sat etc.

type Application

type Application struct {
	Id      string
	Role    string
	Partner string
	Rights  []string
}

type AuthCtxKey

type AuthCtxKey string
const (
	CTX_KEY_TOKEN        AuthCtxKey = "Token"
	CTX_KEY_PERMISSIONS  AuthCtxKey = "Permissions"
	CTX_KEY_CAPABILITIES AuthCtxKey = "Capabilities"
)

func (AuthCtxKey) String

func (c AuthCtxKey) String() string

type AuthResponse

type AuthResponse struct {
	ServiceName     string   `json:"serviceName,omitempty"`
	Username        string   `json:"username,omitempty"`
	FirstName       string   `json:"firstName,omitempty"`
	LastName        string   `json:"lastName,omitempty"`
	Email           string   `json:"email,omitempty"`
	Permissions     []string `json:"permissions,omitempty"`
	OwnershipGroups []string `json:"ownershipGroups,omitempty"`
	OwnershipAdmin  bool     `json:"ownershipAdmin,omitempty"`
	Groups          []string `json:"groups,omitempty"`
}

func NewAuthResponse

func NewAuthResponse(r *http.Request) *AuthResponse

type CanaryMgrConnector

type CanaryMgrConnector struct {
	*HttpClient
	// contains filtered or unexported fields
}

func NewCanaryMgrConnector

func NewCanaryMgrConnector(conf *configuration.Config, tlsConfig *tls.Config) *CanaryMgrConnector

func (*CanaryMgrConnector) CreateCanary

func (c *CanaryMgrConnector) CreateCanary(canaryRequestBody *CanaryRequestBody, isDeepSleepVideoDevice bool, fields log.Fields) error

func (*CanaryMgrConnector) CreateWakeupPool added in v1.0.4

func (c *CanaryMgrConnector) CreateWakeupPool(wakeupPoolRequestBody *WakeupPoolRequestBody, force bool, fields log.Fields) error

func (*CanaryMgrConnector) GetCanaryMgrHost

func (c *CanaryMgrConnector) GetCanaryMgrHost() string

func (*CanaryMgrConnector) SetCanaryMgrHost

func (c *CanaryMgrConnector) SetCanaryMgrHost(host string)

type CanaryRequestBody

type CanaryRequestBody struct {
	Name                   string   `json:"name"`
	DeviceType             string   `json:"deviceType"`
	Size                   int      `json:"size"`
	DistributionPercentage float64  `json:"distributionPercentage"`
	Partner                string   `json:"partner"`
	Model                  string   `json:"model"`
	FwAppliedRule          string   `json:"fwAppliedRule"`
	TimeZones              []string `json:"timeZones"`
	StartPercentRange      float64  `json:"startPercentRange"`
	EndPercentRange        float64  `json:"endPercentRange"`
}

type Claims

type Claims struct {
	ID               string           `json:"jti,omitempty"`
	Issuer           string           `json:"iss,omitempty"`
	ExpiresAt        int64            `json:"exp,omitempty"`
	IssuedAt         int64            `json:"iat,omitempty"`
	NotBefore        int64            `json:"nbf,omitempty"`
	Version          string           `json:"version,omitempty"`
	Subject          string           `json:"sub,omitempty"`
	Audience         []string         `json:"aud,omitempty"`
	Capabilities     []string         `json:"capabilities,omitempty"`
	AllowedResources AllowedResources `json:"allowedResources"`
}

func (*Claims) HasCapability

func (c *Claims) HasCapability(capability string) bool

HasCapability Check if Claims has the given capability

func (*Claims) HasDevice

func (c *Claims) HasDevice(deviceID string) bool

HasDevice Check if Claims has the given device id in AllowedDeviceIDs

func (*Claims) Valid

func (c *Claims) Valid() error

Valid checks that standard claims and sat claims are good

type DefaultIdpService

type DefaultIdpService struct {
	*HttpClient
	*IdpServiceConfig
	// contains filtered or unexported fields
}

func (*DefaultIdpService) GetFullLoginUrl

func (xc *DefaultIdpService) GetFullLoginUrl(continueUrl string) string

func (*DefaultIdpService) GetFullLogoutUrl

func (xc *DefaultIdpService) GetFullLogoutUrl(continueUrl string) string

func (*DefaultIdpService) GetIdpServiceConfig

func (xc *DefaultIdpService) GetIdpServiceConfig() *IdpServiceConfig

func (*DefaultIdpService) GetJsonWebKeyResponse

func (xc *DefaultIdpService) GetJsonWebKeyResponse(url string) *JsonWebKeyResponse

func (*DefaultIdpService) GetToken

func (xc *DefaultIdpService) GetToken(code string) string

func (*DefaultIdpService) IdpServiceHost

func (xc *DefaultIdpService) IdpServiceHost() string

func (*DefaultIdpService) Logout

func (xc *DefaultIdpService) Logout(url string) error

func (*DefaultIdpService) SetIdpServiceHost

func (xc *DefaultIdpService) SetIdpServiceHost(host string)

type EntityMessage

type EntityMessage struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

type ErrInvalidToken

type ErrInvalidToken struct {
	Issues []string
}

ErrInvalidToken ...

func (ErrInvalidToken) Error

func (e ErrInvalidToken) Error() string

type ErrorResponse

type ErrorResponse struct {
	Message string `json:"message"`
}

type ExternalConnectors

type ExternalConnectors struct {
	IdpServiceConnector
	// contains filtered or unexported fields
}

func NewExternalConnectors

func NewExternalConnectors() *ExternalConnectors

type GroupServiceConnector

type GroupServiceConnector struct {
	BaseURL string
	Client  *HttpClient
}

func NewGroupServiceConnector

func NewGroupServiceConnector(conf *configuration.Config, tlsConfig *tls.Config) *GroupServiceConnector

func (*GroupServiceConnector) DoRequest

func (c *GroupServiceConnector) DoRequest(method string, url string, headers map[string]string, body []byte) ([]byte, error)

func (*GroupServiceConnector) GetAllGroups

func (c *GroupServiceConnector) GetAllGroups() (*proto2.XdasHashes, error)

func (*GroupServiceConnector) GetGroupServiceHost added in v1.0.2

func (c *GroupServiceConnector) GetGroupServiceHost() string

func (*GroupServiceConnector) GetGroupsMemberBelongsTo

func (c *GroupServiceConnector) GetGroupsMemberBelongsTo(memberId string) (*proto2.XdasHashes, error)

func (*GroupServiceConnector) SetGroupServiceHost added in v1.0.2

func (c *GroupServiceConnector) SetGroupServiceHost(host string)

type GroupServiceSyncConnector

type GroupServiceSyncConnector struct {
	BaseURL string
	Client  *HttpClient
}

func NewGroupServiceSyncConnector

func NewGroupServiceSyncConnector(conf *configuration.Config, tlsConfig *tls.Config) *GroupServiceSyncConnector

func (*GroupServiceSyncConnector) AddMembersToTag

func (c *GroupServiceSyncConnector) AddMembersToTag(groupId string, members *proto2.XdasHashes) error

func (*GroupServiceSyncConnector) DoRequest

func (c *GroupServiceSyncConnector) DoRequest(method string, url string, headers map[string]string, body []byte) ([]byte, error)

func (*GroupServiceSyncConnector) GetGroupServiceSyncHost added in v1.0.2

func (c *GroupServiceSyncConnector) GetGroupServiceSyncHost() string

func (*GroupServiceSyncConnector) RemoveGroupMembers

func (c *GroupServiceSyncConnector) RemoveGroupMembers(groupId string, member string) error

func (*GroupServiceSyncConnector) SetGroupServiceSyncHost added in v1.0.2

func (c *GroupServiceSyncConnector) SetGroupServiceSyncHost(host string)

type HttpAdminErrorResponse

type HttpAdminErrorResponse struct {
	Status  int    `json:"status"`
	Type    string `json:"type,omitempty"`
	Message string `json:"message"`
}

type HttpClient

type HttpClient struct {
	*http.Client
	// contains filtered or unexported fields
}

func NewHttpClient

func NewHttpClient(conf *configuration.Config, serviceName string, tlsConfig *tls.Config) *HttpClient

func (*HttpClient) Do

func (c *HttpClient) Do(method string, url string, headers map[string]string, bbytes []byte, baseFields log.Fields, loggerName string, retry int) ([]byte, error, bool, int)

Do is a wrapper around http.Client.Do Inputs: method, url, headers, body as bytes (bbytes), fields for logging (baseFields),

external service being called (loggerName), attempt # (retry)

Returns: response body as bytes, any err, whether a retry is useful or not, and the status code

func (*HttpClient) DoWithRetries

func (c *HttpClient) DoWithRetries(method string, url string, inHeaders map[string]string, bbytes []byte, fields log.Fields, loggerName string) ([]byte, error)

type IdpServiceConfig

type IdpServiceConfig struct {
	ClientId        string
	ClientSecret    string
	KidMap          sync.Map // map[string]JsonWebKey
	AuthHeaderValue string
}

type IdpServiceConnector

type IdpServiceConnector interface {
	IdpServiceHost() string
	SetIdpServiceHost(host string)
	GetFullLoginUrl(continueUrl string) string
	GetJsonWebKeyResponse(url string) *JsonWebKeyResponse
	GetFullLogoutUrl(continueUrl string) string
	GetToken(code string) string
	Logout(url string) error
	GetIdpServiceConfig() *IdpServiceConfig
}

func NewIdpServiceConnector

func NewIdpServiceConnector(conf *configuration.Config, externalIdpService IdpServiceConnector) IdpServiceConnector

type JsonWebKey

type JsonWebKey struct {
	KeyType string `json:"kty"`
	E       string `json:"e"`
	Use     string `json:"use"`
	Kid     string `json:"kid"`
	Alg     string `json:"alg"`
	N       string `json:"n"`
}

type JsonWebKeyResponse

type JsonWebKeyResponse struct {
	Keys []JsonWebKey `json:"keys"`
}

type LoginToken

type LoginToken struct {
	Issuer         string
	Subject        string
	Audience       string
	IssuedAt       float64
	ExpirationTime float64
	JwtId          string
	NotValidBefore float64
	LastName       string
	DisplayName    string
	FirstName      string
	PartnerId      string
	Email          string
	Application    []Application
}

func GetLoginTokenFromContext

func GetLoginTokenFromContext(r *http.Request) *LoginToken

func NewLoginToken

func NewLoginToken(claims jwt.MapClaims) *LoginToken

func ValidateAndGetLoginToken

func ValidateAndGetLoginToken(authToken string) (*LoginToken, error)

type ProcessHook

type ProcessHook interface {
	Process(*WebconfigServer, ...interface{})
}

type PublicKeyResponse

type PublicKeyResponse struct {
	Kty string
	//xS256		string
	E   string
	Use string
	Kid string
	X5c []string
	N   string
}

type Validator

type Validator interface {
	Validate(token string) (*Claims, error)
}

Validator is used to check and parse a string to a valid sat token

type WakeupPoolDistribution added in v1.0.4

type WakeupPoolDistribution struct {
	ConfigId          string  `json:"configId"`
	StartPercentRange float64 `json:"startPercentRange"`
	EndPercentRange   float64 `json:"endPercentRange"`
}

type WakeupPoolPercentFilter added in v1.0.4

type WakeupPoolPercentFilter struct {
	Name          string                   `json:"name"`
	DeviceType    string                   `json:"deviceType"`
	Size          int                      `json:"size"`
	Partner       string                   `json:"partner"`
	Model         string                   `json:"model"`
	TimeZones     []string                 `json:"timeZones"`
	Distributions []WakeupPoolDistribution `json:"distributions"`
}

type WakeupPoolRequestBody added in v1.0.4

type WakeupPoolRequestBody struct {
	PercentFilters []WakeupPoolPercentFilter `json:"percentFilters"`
}

Define the request body struct

type WebValidator

type WebValidator struct {
	Client  *http.Client
	KeysURL string

	// storage for retrieved keys
	Keys map[string]interface{}
}

WebValidator implements a Validator using an HTTP client using JWKS

func (*WebValidator) Validate

func (v *WebValidator) Validate(token string) (*Claims, error)

Validate parses the token against the configured JWKS and returns the extracted SAT claims

type WebconfigServer

type WebconfigServer struct {
	XW_XconfServer *xhttp.XconfServer
	*CanaryMgrConnector
	*XcrpConnector
	IdpServiceConnector
	*XconfConnector
	db.DatabaseClient
	*common.ServerConfig
	*GroupServiceConnector
	*GroupServiceSyncConnector
	*taggingapi_config.TaggingApiConfig
	*tracing.XpcTracer

	AppName            string
	ServerOriginId     string
	IdpLoginPath       string
	IdpLogoutPath      string
	IdpLogoutAfterPath string
	IdpCodePath        string
	IdpUrlPath         string
	VerifyStageHost    bool
	// contains filtered or unexported fields
}

func NewWebconfigServer

func NewWebconfigServer(sc *common.ServerConfig, testOnly bool, dc db.DatabaseClient, ec *ExternalConnectors) *WebconfigServer

testOnly=true ==> running unit test

func (*WebconfigServer) AuthValidationMiddleware

func (s *WebconfigServer) AuthValidationMiddleware(next http.Handler) http.Handler

func (*WebconfigServer) MetricsEnabled

func (s *WebconfigServer) MetricsEnabled() bool

func (*WebconfigServer) NoAuthMiddleware

func (s *WebconfigServer) NoAuthMiddleware(next http.Handler) http.Handler

func (*WebconfigServer) NotLoggedHeaders

func (s *WebconfigServer) NotLoggedHeaders() []string

func (*WebconfigServer) TestOnly

func (s *WebconfigServer) TestOnly() bool

func (*WebconfigServer) TestingMiddleware

func (s *WebconfigServer) TestingMiddleware(next http.Handler) http.Handler

func (*WebconfigServer) TlsConfig

func (s *WebconfigServer) TlsConfig() *tls.Config

func (*WebconfigServer) WebMetrics

func (s *WebconfigServer) WebMetrics(m *AppMetrics, next http.Handler) http.Handler

WebMetrics updates infligh, reqSize and respSize metrics

type XResponseWriter

type XResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

func NewXResponseWriter

func NewXResponseWriter(w http.ResponseWriter, vargs ...interface{}) *XResponseWriter

func (*XResponseWriter) Audit

func (w *XResponseWriter) Audit() log.Fields

func (*XResponseWriter) AuditData

func (w *XResponseWriter) AuditData(k string) string

func (*XResponseWriter) AuditId

func (w *XResponseWriter) AuditId() string

func (*XResponseWriter) Body

func (w *XResponseWriter) Body() string

func (*XResponseWriter) Response

func (w *XResponseWriter) Response() string

func (*XResponseWriter) SetAuditData

func (w *XResponseWriter) SetAuditData(k string, v interface{})

func (*XResponseWriter) SetBody

func (w *XResponseWriter) SetBody(body string)

func (*XResponseWriter) SetBodyObfuscated

func (w *XResponseWriter) SetBodyObfuscated(obfuscated bool)

func (*XResponseWriter) StartTime

func (w *XResponseWriter) StartTime() time.Time

func (*XResponseWriter) Status

func (w *XResponseWriter) Status() int

get/set

func (*XResponseWriter) String

func (w *XResponseWriter) String() string

func (*XResponseWriter) Token

func (w *XResponseWriter) Token() string

func (*XResponseWriter) TraceId

func (w *XResponseWriter) TraceId() string

func (*XResponseWriter) Write

func (w *XResponseWriter) Write(b []byte) (int, error)

func (*XResponseWriter) WriteHeader

func (w *XResponseWriter) WriteHeader(status int)

interface/override

type XconfConnector

type XconfConnector struct {
	*HttpClient
	// contains filtered or unexported fields
}

func NewXconfConnector

func NewXconfConnector(conf *configuration.Config, serviceName string, tlsConfig *tls.Config) *XconfConnector

func (*XconfConnector) GetProfiles

func (c *XconfConnector) GetProfiles(urlSuffix string, fields log.Fields) ([]byte, error)

func (*XconfConnector) Host

func (c *XconfConnector) Host() string

func (*XconfConnector) ServiceName

func (c *XconfConnector) ServiceName() string

func (*XconfConnector) SetXconfHost

func (c *XconfConnector) SetXconfHost(host string)

type XcrpConnector

type XcrpConnector struct {
	*HttpClient
	// contains filtered or unexported fields
}

func NewXcrpConnector

func NewXcrpConnector(conf *configuration.Config, tlsConfig *tls.Config) *XcrpConnector

func (*XcrpConnector) GetRecookingStatusFromCanaryMgr

func (c *XcrpConnector) GetRecookingStatusFromCanaryMgr(module string, fields log.Fields) (bool, error)

func (*XcrpConnector) PostRecook

func (c *XcrpConnector) PostRecook(m, p []string, bbytes []byte, fields log.Fields) error

func (*XcrpConnector) SetXcrpHosts

func (c *XcrpConnector) SetXcrpHosts(hosts []string)

func (*XcrpConnector) XcrpHosts

func (c *XcrpConnector) XcrpHosts() []string

Jump to

Keyboard shortcuts

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