Initial release: self-hostable APT repository server and CLI

urapt is a self-hostable APT repository server with a companion CLI for
pushing and managing Debian .deb packages.

Server (urapt-server):
- REST API + APT endpoint, SQLite storage (pure-Go modernc driver, no CGO)
- .deb files stored content-addressed on disk, reference-counted for dedup
- Server-managed RSA-4096 OpenPGP signing key (ProtonMail/go-crypto)
- APT indices (Release/InRelease/Packages[.gz/.xz]) generated on demand
  from the DB, cached in memory, signed with the server key
- Full APT model: repositories -> distributions -> components -> architectures
- Bearer-token auth for REST; HTTP Basic auth for private-repo APT reads
- First registrant becomes admin; repo-scoped permissions
  (read/write/read-write/admin) plus owner and server-admin roles
- Multipart package push with control-field extraction, list/show/delete,
  pool serving, blob ref-count cleanup
- Audit log

CLI (urapt):
- register/login/logout/whoami, token management
- repo/distro/component/arch CRUD, member management
- push/pull/ls/show/rm for packages
- apt-config helper that emits apt setup commands (key, sources.list,
  auth.conf for private repos)

Packaging & docs:
- Dockerfile (multi-stage distroless), docker-compose.yml, sample config
- README quick start, architecture overview, config reference, security notes
- PLAN.md design blueprint, CHANGELOG.md, GPL-3.0 LICENSE
- GitHub Actions CI (test, lint, cross-build for linux/darwin amd64/arm64)
- Makefile release target producing static binaries + tarballs + checksums

Tests cover the data-access layer, auth/permission checks, APT index
generation, .deb parsing, GPG signing, the REST API, and the typed API
client. Verified end-to-end on a Raspberry Pi (arm64) pushing and installing
a real package.
This commit is contained in:
2026-06-28 16:57:34 -05:00
commit 981587e83d
83 changed files with 12812 additions and 0 deletions
+107
View File
@@ -0,0 +1,107 @@
package commands
import (
"fmt"
"net/url"
"strings"
"github.com/spf13/cobra"
"urapt/shared/models"
)
func (r *Root) aptConfigCmd() *cobra.Command {
var component, signedBy string
cmd := &cobra.Command{
Use: "apt-config <repo> <distro>",
Short: "Print apt client configuration (sources.list, key, and auth) for a repository",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
repoName, dist := args[0], args[1]
c, err := r.client()
if err != nil {
return err
}
repo, err := c.GetRepository(repoName)
if err != nil {
return err
}
comps, err := c.ListComponents(repoName, dist)
if err != nil {
return err
}
arches, err := c.ListArchitectures(repoName, dist)
if err != nil {
return err
}
server, err := r.server()
if err != nil {
return err
}
if signedBy == "" {
signedBy = "/usr/share/keyrings/urapt-" + repoName + ".gpg"
}
compList := component
if compList == "" {
var names []string
for _, comp := range comps {
names = append(names, comp.Name)
}
compList = strings.Join(names, " ")
}
if compList == "" {
compList = "main"
}
var archStr string
if len(arches) > 0 {
var names []string
for _, a := range arches {
names = append(names, a.Name)
}
archStr = strings.Join(names, ",")
}
fmt.Println("# 1. Install the repository signing key:")
fmt.Printf("curl -fsSL %s/api/v1/server/pubkey | sudo gpg --dearmor -o %s\n\n", server, signedBy)
fmt.Println("# 2. Add the repository to apt:")
line := fmt.Sprintf("deb [signed-by=%s]", signedBy)
if archStr != "" {
line = fmt.Sprintf("deb [arch=%s signed-by=%s]", archStr, signedBy)
}
line += fmt.Sprintf(" %s/apt/%s/ %s %s", server, repoName, dist, compList)
fmt.Printf("echo '%s' | sudo tee /etc/apt/sources.list.d/%s.list\n\n", line, repoName)
fmt.Println("# 3. Update apt:")
fmt.Println("sudo apt update")
fmt.Println()
if repo.Visibility == models.VisibilityPrivate {
host := hostOf(server)
fmt.Println("# 4. This repository is private. Configure apt credentials:")
fmt.Printf("sudo tee /etc/apt/auth.conf.d/%s.conf <<EOF\n", repoName)
fmt.Printf("machine %s\n", host)
fmt.Printf("login %s\n", r.cfg.Default.User)
tok, _ := r.token()
fmt.Printf("password %s\n", tok)
fmt.Println("EOF")
}
return nil
},
}
cmd.Flags().StringVar(&component, "component", "", "components to enable (default: all in distribution)")
cmd.Flags().StringVar(&signedBy, "signed-by", "", "path for the dearmored keyring")
return cmd
}
// hostOf extracts the host (and port) from a server URL for auth.conf.
func hostOf(server string) string {
u, err := url.Parse(server)
if err != nil {
return server
}
return u.Host
}
+254
View File
@@ -0,0 +1,254 @@
package commands
import (
"fmt"
"github.com/spf13/cobra"
"urapt/cli/interact"
"urapt/cli/output"
)
func (r *Root) loginCmd() *cobra.Command {
var username, password string
cmd := &cobra.Command{
Use: "login [server]",
Short: "Log in to a urapt server and save an API token",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
server := r.flagServer
if len(args) == 1 {
server = args[0]
}
if server == "" {
return fmt.Errorf("server URL required: pass as an argument or --server")
}
if username == "" {
username = r.flagUser
}
if username == "" {
var err error
username, err = interact.ReadLine("Username: ")
if err != nil {
return err
}
}
pw, err := r.resolvePassword(password)
if err != nil {
return err
}
c, err := r.unauthClient(server)
if err != nil {
return err
}
user, token, err := c.Login(username, pw)
if err != nil {
return err
}
if err := r.saveProfile(server, user.Username, token); err != nil {
return err
}
if r.flagJSON {
output.JSON(user)
} else {
fmt.Printf("Logged in as %s (server: %s)\n", user.Username, server)
}
return nil
},
}
cmd.Flags().StringVarP(&username, "username", "u", "", "username")
cmd.Flags().StringVarP(&password, "password", "p", "", "password (prompts if omitted)")
return cmd
}
func (r *Root) logoutCmd() *cobra.Command {
return &cobra.Command{
Use: "logout",
Short: "Revoke the current API token and clear the saved profile",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
if err := c.Logout(); err != nil {
return err
}
if err := r.clearProfile(); err != nil {
return err
}
fmt.Println("Logged out")
return nil
},
}
}
func (r *Root) whoamiCmd() *cobra.Command {
return &cobra.Command{
Use: "whoami",
Short: "Show the currently authenticated user",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
user, err := c.Me()
if err != nil {
return err
}
if r.flagJSON {
output.JSON(user)
} else {
fmt.Printf("%s (admin: %v)\n", user.Username, user.IsAdmin)
}
return nil
},
}
}
func (r *Root) registerCmd() *cobra.Command {
var username, password string
cmd := &cobra.Command{
Use: "register [server]",
Short: "Create a new account on a urapt server (first account becomes admin)",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
server := r.flagServer
if len(args) == 1 {
server = args[0]
}
if server == "" {
return fmt.Errorf("server URL required: pass as an argument or --server")
}
if username == "" {
username = r.flagUser
}
if username == "" {
var err error
username, err = interact.ReadLine("Username: ")
if err != nil {
return err
}
}
pw, err := r.resolvePassword(password)
if err != nil {
return err
}
c, err := r.unauthClient(server)
if err != nil {
return err
}
user, token, err := c.Register(username, pw)
if err != nil {
return err
}
if err := r.saveProfile(server, user.Username, token); err != nil {
return err
}
if r.flagJSON {
output.JSON(user)
} else {
fmt.Printf("Registered and logged in as %s (admin: %v)\n", user.Username, user.IsAdmin)
}
return nil
},
}
cmd.Flags().StringVarP(&username, "username", "u", "", "username")
cmd.Flags().StringVarP(&password, "password", "p", "", "password (prompts if omitted)")
return cmd
}
func (r *Root) tokenCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "token",
Short: "Manage API tokens",
}
cmd.AddCommand(
r.tokenCreateCmd(),
r.tokenListCmd(),
r.tokenRevokeCmd(),
)
return cmd
}
func (r *Root) tokenCreateCmd() *cobra.Command {
var name string
c := &cobra.Command{
Use: "create",
Short: "Create a new API token",
RunE: func(cmd *cobra.Command, args []string) error {
client, err := r.client()
if err != nil {
return err
}
t, err := client.CreateToken(name)
if err != nil {
return err
}
if r.flagJSON {
output.JSON(t)
} else {
fmt.Printf("Token created (name: %s)\n", t.Name)
fmt.Printf(" %s\n", t.Token)
fmt.Println(" Save this token; it will not be shown again.")
}
return nil
},
}
c.Flags().StringVarP(&name, "name", "n", "default", "token label")
return c
}
func (r *Root) tokenListCmd() *cobra.Command {
c := &cobra.Command{
Use: "list",
Short: "List your API tokens",
RunE: func(cmd *cobra.Command, args []string) error {
client, err := r.client()
if err != nil {
return err
}
tokens, err := client.ListTokens()
if err != nil {
return err
}
if r.flagJSON {
output.JSON(tokens)
return nil
}
if len(tokens) == 0 {
fmt.Println("No tokens.")
return nil
}
fmt.Printf("%-12s %-20s %-10s %s\n", "PREFIX", "NAME", "CREATED", "STATUS")
for _, t := range tokens {
status := "active"
if t.RevokedAt != nil {
status = "revoked"
}
fmt.Printf("%-12s %-20s %-10s %s\n", t.Prefix, t.Name, t.CreatedAt[:10], status)
}
return nil
},
}
return c
}
func (r *Root) tokenRevokeCmd() *cobra.Command {
c := &cobra.Command{
Use: "revoke <id>",
Short: "Revoke an API token by id",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := r.client()
if err != nil {
return err
}
if err := client.RevokeToken(args[0]); err != nil {
return err
}
fmt.Println("Token revoked")
return nil
},
}
return c
}
+19
View File
@@ -0,0 +1,19 @@
package commands
import (
"os"
"urapt/cli/interact"
)
// resolvePassword returns the password from a flag, the URAPT_PASSWORD env
// variable, or an interactive prompt (in that order).
func (r *Root) resolvePassword(flag string) (string, error) {
if flag != "" {
return flag, nil
}
if v := os.Getenv("URAPT_PASSWORD"); v != "" {
return v, nil
}
return interact.ReadPassword("Password: ")
}
+257
View File
@@ -0,0 +1,257 @@
package commands
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"urapt/cli/output"
"urapt/shared/apiclient"
"urapt/shared/deb"
"urapt/shared/models"
)
func (r *Root) pushCmd() *cobra.Command {
var archOverride string
cmd := &cobra.Command{
Use: "push <repo> <distro> <component> <file.deb>",
Short: "Upload a .deb package to a repository",
Args: cobra.ExactArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
repo, dist, component, file := args[0], args[1], args[2], args[3]
// Local pre-validation for early, clear errors.
inspected, err := deb.Inspect(file)
if err != nil {
return fmt.Errorf("invalid .deb: %w", err)
}
ctrl := inspected.Control
pkgName, ver, arch := ctrl.Get("Package"), ctrl.Get("Version"), ctrl.Get("Architecture")
if archOverride != "" {
arch = archOverride
}
if r.flagJSON {
// no-op: keep flag accepted
} else {
fmt.Printf("Pushing %s_%s_%s (%d bytes)\n", pkgName, ver, arch, inspected.Size)
}
c, err := r.client()
if err != nil {
return err
}
pkg, err := c.PushPackage(repo, dist, component, file)
if err != nil {
return err
}
if r.flagJSON {
output.JSON(pkg)
} else {
fmt.Printf("Pushed %s_%s_%s to %s/%s/%s\n", pkg.Name, pkg.Version, pkg.Architecture, repo, dist, component)
fmt.Printf(" id: %s\n", pkg.ID)
fmt.Printf(" pool: %s\n", pkg.PoolPath)
fmt.Printf(" sha256: %s\n", pkg.SHA256)
}
return nil
},
}
cmd.Flags().StringVar(&archOverride, "arch", "", "override architecture (rarely needed)")
return cmd
}
func (r *Root) lsCmd() *cobra.Command {
var component, arch, name, query string
cmd := &cobra.Command{
Use: "ls <repo> <distro>",
Short: "List packages in a repository/distribution",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
resp, err := c.ListPackages(args[0], args[1], map[string]string{
"component": component, "arch": arch, "name": name, "q": query,
})
if err != nil {
return err
}
if r.flagJSON {
output.JSON(resp)
return nil
}
if len(resp.Items) == 0 {
fmt.Println("No packages.")
return nil
}
fmt.Printf("%-38s %-20s %-12s %-10s %s\n", "ID", "NAME", "VERSION", "ARCH", "SIZE")
for _, p := range resp.Items {
fmt.Printf("%-38s %-20s %-12s %-10s %d\n", shortID(p.ID), p.Name, p.Version, p.Architecture, p.Size)
}
fmt.Printf("\n%d package(s)\n", resp.Total)
return nil
},
}
cmd.Flags().StringVar(&component, "component", "", "filter by component")
cmd.Flags().StringVar(&arch, "arch", "", "filter by architecture")
cmd.Flags().StringVar(&name, "name", "", "filter by exact name")
cmd.Flags().StringVarP(&query, "query", "q", "", "substring search on name/description")
return cmd
}
func (r *Root) showCmd() *cobra.Command {
var dist string
cmd := &cobra.Command{
Use: "show <repo> <id|name[@version][:arch]>",
Short: "Show package metadata",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
id, err := r.resolvePackageID(c, args[0], dist, args[1])
if err != nil {
return err
}
p, err := c.GetPackage(args[0], id)
if err != nil {
return err
}
if r.flagJSON {
output.JSON(p)
return nil
}
printPackage(p)
return nil
},
}
cmd.Flags().StringVar(&dist, "dist", "", "distribution (required for name-based specs)")
return cmd
}
func (r *Root) pullCmd() *cobra.Command {
var dist, outFile string
cmd := &cobra.Command{
Use: "pull <repo> <id|name[@version][:arch]>",
Short: "Download a package's .deb file",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
id, err := r.resolvePackageID(c, args[0], dist, args[1])
if err != nil {
return err
}
pkg, err := c.GetPackage(args[0], id)
if err != nil {
return err
}
out := outFile
if out == "" {
out = baseName(pkg.PoolPath)
}
if err := c.DownloadPackage(args[0], id, out); err != nil {
return err
}
if outFile != "-" && !r.flagJSON {
fmt.Printf("Downloaded %s\n", out)
}
return nil
},
}
cmd.Flags().StringVar(&dist, "dist", "", "distribution (required for name-based specs)")
cmd.Flags().StringVarP(&outFile, "out", "o", "", "output file (default: original filename; - for stdout)")
return cmd
}
func (r *Root) rmCmd() *cobra.Command {
var dist string
cmd := &cobra.Command{
Use: "rm <repo> <id|name[@version][:arch]>",
Short: "Delete a package",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
id, err := r.resolvePackageID(c, args[0], dist, args[1])
if err != nil {
return err
}
if err := c.DeletePackage(args[0], id); err != nil {
return err
}
fmt.Printf("Deleted package %s\n", id)
return nil
},
}
cmd.Flags().StringVar(&dist, "dist", "", "distribution (required for name-based specs)")
return cmd
}
// resolvePackageID resolves a spec ("id" or "name[@version][:arch]") to a
// package id. UUID specs are returned as-is. Name specs require --dist.
func (r *Root) resolvePackageID(c *apiclient.Client, repo, dist, spec string) (string, error) {
id, name, version, arch := apiclient.ParsePackageSpec(spec)
if id != "" {
return id, nil
}
if dist == "" {
return "", fmt.Errorf("name-based spec %q requires --dist", spec)
}
filters := map[string]string{"name": name}
resp, err := c.ListPackages(repo, dist, filters)
if err != nil {
return "", err
}
for _, p := range resp.Items {
if version != "" && p.Version != version {
continue
}
if arch != "" && p.Architecture != arch {
continue
}
return p.ID, nil
}
return "", fmt.Errorf("no package matching %s in %s/%s", spec, repo, dist)
}
// printPackage prints a package's metadata in a readable key: value form.
func printPackage(p *models.Package) {
fmt.Printf("id: %s\n", p.ID)
fmt.Printf("name: %s\n", p.Name)
fmt.Printf("version: %s\n", p.Version)
fmt.Printf("architecture: %s\n", p.Architecture)
fmt.Printf("source: %s\n", p.Source)
fmt.Printf("maintainer: %s\n", p.Maintainer)
fmt.Printf("section: %s\n", p.Section)
fmt.Printf("priority: %s\n", p.Priority)
fmt.Printf("homepage: %s\n", p.Homepage)
fmt.Printf("depends: %s\n", p.Depends)
fmt.Printf("description: %s\n", p.Description)
fmt.Printf("pool_path: %s\n", p.PoolPath)
fmt.Printf("size: %d\n", p.Size)
fmt.Printf("sha256: %s\n", p.SHA256)
fmt.Printf("created_at: %s\n", p.CreatedAt)
}
// shortID returns the first 8 chars of a UUID for compact display.
func shortID(id string) string {
if len(id) >= 8 {
return id[:8]
}
return id
}
// baseName returns the last path segment.
func baseName(p string) string {
if i := strings.LastIndexByte(p, '/'); i >= 0 {
return p[i+1:]
}
return p
}
+320
View File
@@ -0,0 +1,320 @@
package commands
import (
"fmt"
"os"
"github.com/spf13/cobra"
"urapt/cli/output"
)
func (r *Root) repoCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "repo",
Short: "Manage repositories",
}
cmd.AddCommand(
r.repoCreateCmd(),
r.repoListCmd(),
r.repoInfoCmd(),
r.repoSetVisibilityCmd(),
r.repoDeleteCmd(),
r.repoPubkeyCmd(),
r.repoMembersCmd(),
)
return cmd
}
func (r *Root) repoCreateCmd() *cobra.Command {
var visibility, description string
var public, private bool
cmd := &cobra.Command{
Use: "create <name>",
Short: "Create a new repository",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
vis := visibility
if public {
vis = "public"
} else if private {
vis = "private"
}
if vis == "" {
vis = "private"
}
c, err := r.client()
if err != nil {
return err
}
repo, err := c.CreateRepository(args[0], vis, description)
if err != nil {
return err
}
if r.flagJSON {
output.JSON(repo)
} else {
fmt.Printf("Created repository %s (%s)\n", repo.Name, repo.Visibility)
}
return nil
},
}
cmd.Flags().StringVar(&visibility, "visibility", "", "public or private")
cmd.Flags().BoolVar(&public, "public", false, "shorthand for --visibility=public")
cmd.Flags().BoolVar(&private, "private", false, "shorthand for --visibility=private")
cmd.Flags().StringVarP(&description, "description", "d", "", "repository description")
return cmd
}
func (r *Root) repoListCmd() *cobra.Command {
return &cobra.Command{
Use: "list",
Short: "List repositories visible to you",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
repos, err := c.ListRepositories()
if err != nil {
return err
}
if r.flagJSON {
output.JSON(repos)
return nil
}
if len(repos) == 0 {
fmt.Println("No repositories.")
return nil
}
fmt.Printf("%-20s %-10s %s\n", "NAME", "VISIBILITY", "DESCRIPTION")
for _, repo := range repos {
fmt.Printf("%-20s %-10s %s\n", repo.Name, repo.Visibility, repo.Description)
}
return nil
},
}
}
func (r *Root) repoInfoCmd() *cobra.Command {
return &cobra.Command{
Use: "info <name>",
Short: "Show details of a repository",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
repo, err := c.GetRepository(args[0])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(repo)
return nil
}
fmt.Printf("name: %s\n", repo.Name)
fmt.Printf("visibility: %s\n", repo.Visibility)
fmt.Printf("description: %s\n", repo.Description)
fmt.Printf("created: %s\n", repo.CreatedAt)
return nil
},
}
}
func (r *Root) repoSetVisibilityCmd() *cobra.Command {
var public, private bool
cmd := &cobra.Command{
Use: "set-visibility <name>",
Short: "Change a repository's visibility",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
vis := ""
if public {
vis = "public"
} else if private {
vis = "private"
}
if vis == "" {
return fmt.Errorf("pass --public or --private")
}
c, err := r.client()
if err != nil {
return err
}
repo, err := c.UpdateRepository(args[0], nil, &vis, nil)
if err != nil {
return err
}
if r.flagJSON {
output.JSON(repo)
} else {
fmt.Printf("Updated %s: visibility=%s\n", repo.Name, repo.Visibility)
}
return nil
},
}
cmd.Flags().BoolVar(&public, "public", false, "make public")
cmd.Flags().BoolVar(&private, "private", false, "make private")
return cmd
}
func (r *Root) repoDeleteCmd() *cobra.Command {
return &cobra.Command{
Use: "delete <name>",
Short: "Delete a repository and all its packages",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
if err := c.DeleteRepository(args[0]); err != nil {
return err
}
fmt.Printf("Deleted repository %s\n", args[0])
return nil
},
}
}
func (r *Root) repoPubkeyCmd() *cobra.Command {
var outFile string
cmd := &cobra.Command{
Use: "pubkey <name>",
Short: "Print the server's armored public key for a repository",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
pub, err := c.RepositoryPubkey(args[0])
if err != nil {
return err
}
if outFile != "" {
return os.WriteFile(outFile, []byte(pub), 0o644)
}
fmt.Print(pub)
return nil
},
}
cmd.Flags().StringVarP(&outFile, "out", "o", "", "write to file instead of stdout")
return cmd
}
func (r *Root) repoMembersCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "members",
Short: "Manage repository members",
}
cmd.AddCommand(
r.repoMembersListCmd(),
r.repoMembersAddCmd(),
r.repoMembersUpdateCmd(),
r.repoMembersRemoveCmd(),
)
return cmd
}
func (r *Root) repoMembersListCmd() *cobra.Command {
return &cobra.Command{
Use: "list <repo>",
Short: "List members of a repository",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
members, err := c.ListMembers(args[0])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(members)
return nil
}
fmt.Printf("%-20s %s\n", "USER", "ACCESS")
for _, m := range members {
fmt.Printf("%-20s %s\n", m.User.Username, m.Access)
}
return nil
},
}
}
func (r *Root) repoMembersAddCmd() *cobra.Command {
var access string
cmd := &cobra.Command{
Use: "add <repo> <username>",
Short: "Grant a user access to a repository",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
m, err := c.AddMember(args[0], args[1], access)
if err != nil {
return err
}
if r.flagJSON {
output.JSON(m)
} else {
fmt.Printf("Granted %s access=%s on %s\n", m.User.Username, m.Access, args[0])
}
return nil
},
}
cmd.Flags().StringVarP(&access, "access", "a", "read", "read, write, read-write, or admin")
return cmd
}
func (r *Root) repoMembersUpdateCmd() *cobra.Command {
var access string
cmd := &cobra.Command{
Use: "update <repo> <username>",
Short: "Change a member's access level",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
m, err := c.UpdateMember(args[0], args[1], access)
if err != nil {
return err
}
if r.flagJSON {
output.JSON(m)
} else {
fmt.Printf("Updated %s access=%s on %s\n", m.User.Username, m.Access, args[0])
}
return nil
},
}
cmd.Flags().StringVarP(&access, "access", "a", "", "read, write, read-write, or admin")
return cmd
}
func (r *Root) repoMembersRemoveCmd() *cobra.Command {
return &cobra.Command{
Use: "remove <repo> <username>",
Short: "Revoke a user's access to a repository",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
if err := c.RemoveMember(args[0], args[1]); err != nil {
return err
}
fmt.Printf("Removed %s from %s\n", args[1], args[0])
return nil
},
}
}
+168
View File
@@ -0,0 +1,168 @@
// Package commands implements the urapt CLI command tree using cobra.
package commands
import (
"fmt"
"os"
"github.com/spf13/cobra"
"urapt/cli/config"
"urapt/shared/apiclient"
)
// Root holds the urapt CLI runtime state: the version, loaded config, and
// flag overrides. It builds and executes the cobra command tree.
type Root struct {
version string
cfg *config.File
flagServer string
flagUser string
flagToken string
flagJSON bool
rootCmd *cobra.Command
}
// New constructs the CLI root.
func New(version string) *Root {
r := &Root{version: version}
r.build()
return r
}
// Execute runs the command tree with the given args.
func (r *Root) Execute(args []string) error {
r.rootCmd.SetArgs(args)
err := r.rootCmd.Execute()
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
return err
}
// build constructs the cobra root and attaches subcommands.
func (r *Root) build() {
r.rootCmd = &cobra.Command{
Use: "urapt",
Short: "urapt is a CLI for managing packages on a self-hosted urapt APT server",
Long: "urapt pushes and manages Debian packages on a self-hosted urapt\n" +
"server. Log in once, then push .deb files to your repositories.",
SilenceUsage: true,
SilenceErrors: true,
}
r.rootCmd.PersistentFlags().StringVar(&r.flagServer, "server", "", "urapt server URL (overrides config)")
r.rootCmd.PersistentFlags().StringVar(&r.flagUser, "user", "", "username (overrides config)")
r.rootCmd.PersistentFlags().StringVar(&r.flagToken, "token", "", "API token (overrides config)")
r.rootCmd.PersistentFlags().BoolVar(&r.flagJSON, "json", false, "output JSON")
r.rootCmd.AddCommand(
r.versionCmd(),
r.loginCmd(),
r.logoutCmd(),
r.whoamiCmd(),
r.registerCmd(),
r.tokenCmd(),
r.repoCmd(),
r.distroCmd(),
r.componentCmd(),
r.archCmd(),
r.pushCmd(),
r.pullCmd(),
r.lsCmd(),
r.showCmd(),
r.rmCmd(),
r.aptConfigCmd(),
)
}
// loadConfig lazily loads the CLI config file (once).
func (r *Root) loadConfig() error {
if r.cfg != nil {
return nil
}
cfg, err := config.Load()
if err != nil {
return err
}
r.cfg = cfg
return nil
}
// server resolves the effective server URL (flag > env > config).
func (r *Root) server() (string, error) {
if err := r.loadConfig(); err != nil {
return "", err
}
if r.flagServer != "" {
return r.flagServer, nil
}
if v := os.Getenv("URAPT_SERVER"); v != "" {
return v, nil
}
if r.cfg.Default.Server != "" {
return r.cfg.Default.Server, nil
}
return "", fmt.Errorf("no server configured: run `urapt login <server>` or pass --server")
}
// token resolves the effective API token (flag > env > config).
func (r *Root) token() (string, error) {
if r.flagToken != "" {
return r.flagToken, nil
}
if v := os.Getenv("URAPT_TOKEN"); v != "" {
return v, nil
}
if err := r.loadConfig(); err != nil {
return "", err
}
if r.cfg.Default.Token != "" {
return r.cfg.Default.Token, nil
}
return "", fmt.Errorf("not logged in: run `urapt login`")
}
// client builds an authenticated client using the resolved server + token.
func (r *Root) client() (*apiclient.Client, error) {
server, err := r.server()
if err != nil {
return nil, err
}
tok, _ := r.token()
return apiclient.New(server, tok), nil
}
// unauthClient builds a client with only the server resolved (for login/register).
func (r *Root) unauthClient(server string) (*apiclient.Client, error) {
if server == "" {
var err error
server, err = r.server()
if err != nil {
return nil, err
}
}
return apiclient.New(server, ""), nil
}
// saveProfile persists the given server/user/token as the default profile.
func (r *Root) saveProfile(server, user, token string) error {
if err := r.loadConfig(); err != nil {
return err
}
r.cfg.Default.Server = server
r.cfg.Default.User = user
r.cfg.Default.Token = token
return config.Save(r.cfg)
}
// clearProfile removes the stored token (used by logout).
func (r *Root) clearProfile() error {
if err := r.loadConfig(); err != nil {
return err
}
r.cfg.Default.Token = ""
return config.Save(r.cfg)
}
+243
View File
@@ -0,0 +1,243 @@
package commands
import (
"fmt"
"github.com/spf13/cobra"
"urapt/cli/output"
)
func (r *Root) distroCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "distro",
Short: "Manage distributions (suites) within a repository",
}
cmd.AddCommand(r.distroCreateCmd(), r.distroListCmd(), r.distroDeleteCmd())
return cmd
}
func (r *Root) distroCreateCmd() *cobra.Command {
return &cobra.Command{
Use: "create <repo> <distro>",
Short: "Add a distribution to a repository",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
d, err := c.CreateDistribution(args[0], args[1])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(d)
} else {
fmt.Printf("Created distribution %s in %s\n", d.Name, args[0])
}
return nil
},
}
}
func (r *Root) distroListCmd() *cobra.Command {
return &cobra.Command{
Use: "list <repo>",
Short: "List distributions in a repository",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
dists, err := c.ListDistributions(args[0])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(dists)
return nil
}
for _, d := range dists {
fmt.Println(d.Name)
}
return nil
},
}
}
func (r *Root) distroDeleteCmd() *cobra.Command {
return &cobra.Command{
Use: "delete <repo> <distro>",
Short: "Delete a distribution and its packages",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
if err := c.DeleteDistribution(args[0], args[1]); err != nil {
return err
}
fmt.Printf("Deleted distribution %s in %s\n", args[1], args[0])
return nil
},
}
}
func (r *Root) componentCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "component",
Short: "Manage components within a distribution",
}
cmd.AddCommand(r.componentCreateCmd(), r.componentListCmd(), r.componentDeleteCmd())
return cmd
}
func (r *Root) componentCreateCmd() *cobra.Command {
return &cobra.Command{
Use: "create <repo> <distro> <component>",
Short: "Add a component to a distribution",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
comp, err := c.CreateComponent(args[0], args[1], args[2])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(comp)
} else {
fmt.Printf("Created component %s in %s/%s\n", comp.Name, args[0], args[1])
}
return nil
},
}
}
func (r *Root) componentListCmd() *cobra.Command {
return &cobra.Command{
Use: "list <repo> <distro>",
Short: "List components in a distribution",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
comps, err := c.ListComponents(args[0], args[1])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(comps)
return nil
}
for _, comp := range comps {
fmt.Println(comp.Name)
}
return nil
},
}
}
func (r *Root) componentDeleteCmd() *cobra.Command {
return &cobra.Command{
Use: "delete <repo> <distro> <component>",
Short: "Delete a component",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
if err := c.DeleteComponent(args[0], args[1], args[2]); err != nil {
return err
}
fmt.Printf("Deleted component %s in %s/%s\n", args[2], args[0], args[1])
return nil
},
}
}
func (r *Root) archCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "arch",
Short: "Manage architectures within a distribution",
}
cmd.AddCommand(r.archAddCmd(), r.archListCmd(), r.archRemoveCmd())
return cmd
}
func (r *Root) archAddCmd() *cobra.Command {
return &cobra.Command{
Use: "add <repo> <distro> <arch>",
Short: "Add an architecture to a distribution",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
a, err := c.CreateArchitecture(args[0], args[1], args[2])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(a)
} else {
fmt.Printf("Added architecture %s to %s/%s\n", a.Name, args[0], args[1])
}
return nil
},
}
}
func (r *Root) archListCmd() *cobra.Command {
return &cobra.Command{
Use: "list <repo> <distro>",
Short: "List architectures in a distribution",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
arches, err := c.ListArchitectures(args[0], args[1])
if err != nil {
return err
}
if r.flagJSON {
output.JSON(arches)
return nil
}
for _, a := range arches {
fmt.Println(a.Name)
}
return nil
},
}
}
func (r *Root) archRemoveCmd() *cobra.Command {
return &cobra.Command{
Use: "remove <repo> <distro> <arch>",
Short: "Remove an architecture from a distribution",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := r.client()
if err != nil {
return err
}
if err := c.DeleteArchitecture(args[0], args[1], args[2]); err != nil {
return err
}
fmt.Printf("Removed architecture %s from %s/%s\n", args[2], args[0], args[1])
return nil
},
}
}
+17
View File
@@ -0,0 +1,17 @@
package commands
import (
"fmt"
"github.com/spf13/cobra"
)
func (r *Root) versionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print the urapt CLI version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(r.version)
},
}
}
+75
View File
@@ -0,0 +1,75 @@
// Package config manages the urapt CLI's local configuration: the server URL,
// username, and API token stored in ~/.config/urapt/config.toml (perm 0600).
package config
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
)
// File is the on-disk CLI config shape.
type File struct {
Default Profile `toml:"default"`
}
// Profile is the active connection profile.
type Profile struct {
Server string `toml:"server"`
User string `toml:"user"`
Token string `toml:"token"`
}
// configPath returns the path to the CLI config file.
func configPath() (string, error) {
dir, err := os.UserConfigDir()
if err != nil {
dir = os.Getenv("HOME")
dir = filepath.Join(dir, ".config")
}
return filepath.Join(dir, "urapt", "config.toml"), nil
}
// Load reads the CLI config, returning an empty config if none exists.
func Load() (*File, error) {
path, err := configPath()
if err != nil {
return nil, err
}
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return &File{}, nil
}
return nil, fmt.Errorf("read config: %w", err)
}
var f File
if err := toml.Unmarshal(data, &f); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
f.Default.Server = strings.TrimRight(f.Default.Server, "/")
return &f, nil
}
// Save writes the CLI config with 0600 permissions.
func Save(f *File) error {
path, err := configPath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return fmt.Errorf("create config dir: %w", err)
}
var buf strings.Builder
enc := toml.NewEncoder(&buf)
if err := enc.Encode(f); err != nil {
return fmt.Errorf("encode config: %w", err)
}
return os.WriteFile(path, []byte(buf.String()), 0o600)
}
// Path returns the config file path (for display).
func Path() (string, error) { return configPath() }
+40
View File
@@ -0,0 +1,40 @@
// Package interact provides simple interactive prompts (passwords, confirms).
package interact
import (
"fmt"
"os"
"strings"
"golang.org/x/term"
)
// ReadPassword prompts for a password with input hidden.
func ReadPassword(prompt string) (string, error) {
fmt.Fprint(os.Stderr, prompt)
b, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
return string(b), nil
}
// ReadLine prompts and reads a single line of input.
func ReadLine(prompt string) (string, error) {
fmt.Fprint(os.Stderr, prompt)
var s string
if _, err := fmt.Fscanln(os.Stdin, &s); err != nil {
return "", err
}
return strings.TrimSpace(s), nil
}
// Confirm prompts a yes/no question, returning the boolean answer.
func Confirm(prompt string) bool {
fmt.Fprintf(os.Stderr, "%s [y/N]: ", prompt)
var s string
fmt.Fscanln(os.Stdin, &s)
s = strings.ToLower(strings.TrimSpace(s))
return s == "y" || s == "yes"
}
+24
View File
@@ -0,0 +1,24 @@
// Package output provides small formatting helpers for CLI commands.
package output
import (
"encoding/json"
"fmt"
"os"
)
// JSON prints v as indented JSON.
func JSON(v any) {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(v)
}
// Printf is a thin wrapper around fmt.Printf.
func Printf(format string, args ...any) { fmt.Printf(format, args...) }
// Println prints a line.
func Println(args ...any) { fmt.Println(args...) }
// Errorf prints to stderr.
func Errorf(format string, args ...any) { fmt.Fprintf(os.Stderr, format, args...) }