web_ui

package
v0.0.0-...-7159a71 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: Apache-2.0 Imports: 86 Imported by: 0

README

A short README explaining our authorization permissions, specifically regarding tokens received from the URL or Header vs the login cookie.

Tokens that are part of the HTTP Request Header e.g. {"Authorization": "Bearer +"<token>} and that are set in the URL Query via Authz are considered valid if they are signed by either the Federation jwk or the Origin jwk.

However, tokens that are retrieved from the login cookie ctx.Cookie("login") are ONLY valid if the are signed by the Origin jwk. This can be seen in the prometheus code and how it accesses the functions in Authorization.go

Documentation

Overview

**************************************************************

*
* Copyright (C) 2024, Pelican Project, Morgridge Institute for Research
*
* 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.
*
**************************************************************

Index

Constants

View Source
const (
	GroupSourceTypeOIDC     string = "oidc"
	GroupSourceTypeFile     string = "file"
	GroupSourceTypeInternal string = "internal"
	GroupSourceTypeGitHub   string = "github"
)

Group source types

View Source
const (
	MaxLabelLimit            = 128
	MaxLabelNameLengthLimit  = 256
	MaxLabelValueLengthLimit = 4096
	MaxSampleLimit           = 800
)

Variables

View Source
var ErrNotReady = errors.New("Scrape manager not ready")

ErrNotReady is returned if the underlying scrape manager is not ready yet.

Functions

func AdminAuthHandler

func AdminAuthHandler(ctx *gin.Context)

adminAuthHandler checks the admin status of a logged-in user. This middleware should be cascaded behind the web_ui.AuthHandler

func AuthHandler

func AuthHandler(ctx *gin.Context)

Check if user is authenticated by checking if the "login" cookie is present and set the user identity to ctx

func CheckAdmin

func CheckAdmin(user string, groups []string) (isAdmin bool, message string)

checkAdmin checks if a user string has admin privilege. It returns boolean and a message indicating the error message.

Note that by default it only checks if user == "admin". If you have a custom list of admin identifiers to check, you should set Server.UIAdminUsers. If you want to grant admin privileges based on group membership, you should set Server.AdminGroups.

func ConfigOAuthClientAPIs

func ConfigOAuthClientAPIs(engine *gin.Engine) error

Configure OAuth2 client and register related authentication endpoints for Web UI

func ConfigureEmbeddedPrometheus

func ConfigureEmbeddedPrometheus(ctx context.Context, engine *gin.Engine, dialContextFunc func(context.Context, string, string) (net.Conn, error)) error

func ConfigureServerWebAPI added in v1.0.4

func ConfigureServerWebAPI(ctx context.Context, engine *gin.Engine, egrp *errgroup.Group) error

Configure endpoints for server web APIs. This function does not configure any UI specific paths but just redirect root path to /view.

You need to mount the static resources for UI in a separate function

func DowntimeAuthHandler

func DowntimeAuthHandler(ctx *gin.Context)

DowntimeAuthHandler allows EITHER: 1. Admin cookie authentication (req from this server itself), OR 2. Server bearer token authentication (req from another server, i.e. origin/cache)

func GenerateCSRFCookie

func GenerateCSRFCookie(ctx *gin.Context, metadata map[string]string) (string, error)

Generate a 16B random string and set as the value of ctx session key "oauthstate" return a string for OAuth2 "state" query parameter including the random string and other metadata

func GenerateOAuthState

func GenerateOAuthState(metadata map[string]string) string

Generate the state for the authentication request in OAuth2 code flow. The metadata are formatted similar to url query parameters:

key1=val1&key2=val2

where values are url-encoded. We then base64 encode the resulting string in order to ensure that over-zealous providers do not treat the final URL as a double-encoding attack or somesuch.

func GetEngine

func GetEngine() (*gin.Engine, error)

func GetSessionHandler

func GetSessionHandler() (gin.HandlerFunc, error)

Setup and return the session handler for web UI APIs. Calling multiple times will only set up the handler once

func GetUserGroups

func GetUserGroups(ctx *gin.Context) (user string, userId string, groups []string, err error)

Get user information including userId from the login cookie or Bearer token. Returns username, userId, sub, issuer, groups, and error.

func HandleCreateDowntime

func HandleCreateDowntime(ctx *gin.Context)

func HandleDeleteDowntime

func HandleDeleteDowntime(ctx *gin.Context)

func HandleDeleteLogLevel

func HandleDeleteLogLevel(ctx *gin.Context)

HandleDeleteLogLevel handles DELETE requests to remove a temporary log level change

func HandleGetDowntime

func HandleGetDowntime(ctx *gin.Context)

func HandleGetDowntimeByUUID

func HandleGetDowntimeByUUID(ctx *gin.Context)

func HandleGetLogLevel

func HandleGetLogLevel(ctx *gin.Context)

HandleGetLogLevel handles GET requests to retrieve current log level status

func HandleGetServerLocalMetadataHistory

func HandleGetServerLocalMetadataHistory(ctx *gin.Context)

HandleGetServerLocalMetadataHistory returns the locally cached server metadata history for Origins/Caches.

func HandleSetLogLevel

func HandleSetLogLevel(ctx *gin.Context)

HandleSetLogLevel handles POST requests to temporarily change log level

func HandleUpdateDowntime

func HandleUpdateDowntime(ctx *gin.Context)

func InitServerWebLogin added in v1.0.4

func InitServerWebLogin(ctx context.Context) error

Setup the initial server web login by sending the one-time code to stdout and record health status of the WebUI based on the success of the initialization

func ParseOAuthState

func ParseOAuthState(state string) (metadata map[string]string, err error)

Parse the OAuth2 callback state into a key-val map. Error if keys are duplicated state is the url-decoded value of the query parameter "state" in the the OAuth2 callback request

func RequireAuthMiddleware

func RequireAuthMiddleware(ctx *gin.Context)

Require auth; if missing, redirect to the login endpoint.

The current implementation forces the OAuth2 endpoint; future work may instead use a generic login page.

func RunEngine

func RunEngine(ctx context.Context, engine *gin.Engine, egrp *errgroup.Group) error

Run the gin engine in the current goroutine.

Will use a background golang routine to periodically reload the certificate utilized by the UI.

func RunEngineRoutine

func RunEngineRoutine(ctx context.Context, engine *gin.Engine, egrp *errgroup.Group, curRoutine bool) error

Run the gin engine; if curRoutine is false, it will run in a background goroutine.

func RunEngineRoutineWithListener

func RunEngineRoutineWithListener(ctx context.Context, engine *gin.Engine, egrp *errgroup.Group, curRoutine bool, ln net.Listener) error

Run the web engine connected to a provided listener `ln`.

func ServerHeaderMiddleware

func ServerHeaderMiddleware(ctx *gin.Context)

func WritePasswordEntry added in v1.0.4

func WritePasswordEntry(user, password string) error

Types

type AddGroupMemberReq

type AddGroupMemberReq struct {
	UserID string `json:"userId"`
}

type AddUserReq

type AddUserReq struct {
	Username string `json:"username"`
	Sub      string `json:"sub"`
	Issuer   string `json:"issuer"`
}

type CreateApiTokenReq

type CreateApiTokenReq struct {
	Name       string   `json:"name"`
	Expiration string   `json:"expiration"` // RFC3339 format, if not provided or "never" or "", token will not expire
	Scopes     []string `json:"scopes"`
}

type CreateGroupReq

type CreateGroupReq struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

type DowntimeInput

type DowntimeInput struct {
	CreatedBy   string                  `json:"createdBy"`  // Person who created this downtime
	UpdatedBy   string                  `json:"updatedBy"`  // Person who last updated this downtime
	ServerName  string                  `json:"serverName"` // Empty for Origin/Cache input; Not empty for Registry input
	ServerID    string                  `json:"serverId"`
	Source      string                  `json:"source"` // Automatically set by the server; should only be set by input during testing
	Class       server_structs.Class    `json:"class"`
	Description string                  `json:"description"`
	Severity    server_structs.Severity `json:"severity"`
	StartTime   int64                   `json:"startTime"` // Epoch UTC in seconds
	EndTime     int64                   `json:"endTime"`   // Epoch UTC in seconds
}

type InitLogin added in v1.0.4

type InitLogin struct {
	Code string `form:"code"`
}

type LogLevelChangeResponse

type LogLevelChangeResponse struct {
	ChangeID      string    `json:"changeId"`
	Level         string    `json:"level"`
	ParameterName string    `json:"parameterName,omitempty"`
	EndTime       time.Time `json:"endTime"`
	Remaining     int       `json:"remainingSeconds"`
}

LogLevelChangeResponse represents a log level change with its metadata

type LogLevelStatusResponse

type LogLevelStatusResponse struct {
	CurrentLevel  string                   `json:"currentLevel"`
	BaseLevel     string                   `json:"baseLevel"`
	ActiveChanges []LogLevelChangeResponse `json:"activeChanges"`
	Parameters    []ParameterLevelStatus   `json:"parameters"`
}

LogLevelStatusResponse represents the current log level status

type Login added in v1.0.4

type Login struct {
	User     string `form:"user"`
	Password string `form:"password"`
}

type LogrusAdapter added in v1.0.4

type LogrusAdapter struct {
	*logrus.Logger
	// contains filtered or unexported fields
}

func (LogrusAdapter) Log added in v1.0.4

func (a LogrusAdapter) Log(keyvals ...interface{}) error

Log method which satisfies the kitlog.Logger interface. It also propragates field level and field message to top level log

type OIDCEnabledServerRes

type OIDCEnabledServerRes struct {
	ODICEnabledServers []string `json:"oidc_enabled_servers"`
}

type ParameterLevelStatus

type ParameterLevelStatus struct {
	ParameterName string `json:"parameterName"`
	CurrentLevel  string `json:"currentLevel"`
	BaseLevel     string `json:"baseLevel"`
}

ParameterLevelStatus summarizes the current/base level for a parameter.

type PasswordReset added in v1.0.4

type PasswordReset struct {
	Password string `form:"password"`
}

type ReadyHandler

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

func (*ReadyHandler) SetReady

func (h *ReadyHandler) SetReady(v bool)

type SetLogLevelRequest

type SetLogLevelRequest struct {
	Level         string `json:"level" binding:"required"`          // Log level (e.g., "debug", "info", "warn", "error")
	Duration      int    `json:"duration" binding:"required,min=1"` // Duration in seconds
	ParameterName string `json:"parameterName"`                     // Parameter name like "Logging.Level" or "Logging.Origin.Xrootd"
}

SetLogLevelRequest represents a request to temporarily change log level

type UserRole

type UserRole string
const (
	AdminRole    UserRole = "admin"
	NonAdminRole UserRole = "user"
)

type WhoAmIRes

type WhoAmIRes struct {
	Authenticated bool     `json:"authenticated"`
	Role          UserRole `json:"role"`
	User          string   `json:"user"`
}

Jump to

Keyboard shortcuts

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