Compare commits
16 Commits
api-dev
...
cdaceb1cf7
| Author | SHA1 | Date | |
|---|---|---|---|
| cdaceb1cf7 | |||
| 43bff4513a | |||
| ed2f921b0f | |||
| e693a7616c | |||
| 548681face | |||
| c115f41dac | |||
| 69802f3ece | |||
| e7d20360a2 | |||
| 1d0c075d68 | |||
| b95084ddc3 | |||
| 4885622d6a | |||
| 66ffa3d3fb | |||
| 6901f6fcc4 | |||
| 47b90fee87 | |||
| 43fe875cde | |||
| 35252fa1e8 |
31
.env.example
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
# Django settings
|
||||||
|
KEYWARDEN_SECRET_KEY=supersecret
|
||||||
|
KEYWARDEN_DEBUG=True
|
||||||
|
KEYWARDEN_ALLOWED_HOSTS=*
|
||||||
|
KEYWARDEN_TRUSTED_ORIGINS=https://reverse.proxy.domain.xyz,https://127.0.0.1
|
||||||
|
KEYWARDEN_DOMAIN=https://example.domain.xyz
|
||||||
|
|
||||||
|
# Database
|
||||||
|
KEYWARDEN_POSTGRES_DB=keywarden
|
||||||
|
KEYWARDEN_POSTGRES_USER=keywarden
|
||||||
|
KEYWARDEN_POSTGRES_PASSWORD=postgres
|
||||||
|
KEYWARDEN_POSTGRES_HOST=keywarden-db
|
||||||
|
KEYWARDEN_POSTGRES_PORT=5432
|
||||||
|
|
||||||
|
|
||||||
|
# Admin
|
||||||
|
KEYWARDEN_ADMIN_USERNAME=admin
|
||||||
|
KEYWARDEN_ADMIN_EMAIL=admin@example.com
|
||||||
|
KEYWARDEN_ADMIN_PASSWORD=password
|
||||||
|
|
||||||
|
# Auth mode: native | oidc | hybrid
|
||||||
|
KEYWARDEN_AUTH_MODE=native
|
||||||
|
|
||||||
|
|
||||||
|
# OIDC (optional)
|
||||||
|
# KEYWARDEN_OIDC_CLIENT_ID=
|
||||||
|
# KEYWARDEN_OIDC_CLIENT_SECRET=
|
||||||
|
# KEYWARDEN_OIDC_AUTHORIZATION_ENDPOINT=
|
||||||
|
# KEYWARDEN_OIDC_TOKEN_ENDPOINT=
|
||||||
|
# KEYWARDEN_OIDC_USER_ENDPOINT=
|
||||||
|
# KEYWARDEN_OIDC_JWKS_ENDPOINT=
|
||||||
3
.gitignore
vendored
@@ -218,9 +218,6 @@ __marimo__/
|
|||||||
# Certificates
|
# Certificates
|
||||||
*.pem
|
*.pem
|
||||||
|
|
||||||
# Docker
|
|
||||||
*compose.yml
|
|
||||||
|
|
||||||
nginx/logs/*
|
nginx/logs/*
|
||||||
nginx/certs/*.pem
|
nginx/certs/*.pem
|
||||||
|
|
||||||
|
|||||||
10
API_DOCS.md
@@ -13,3 +13,13 @@ Authentication:
|
|||||||
Notes:
|
Notes:
|
||||||
- Base URL for v1 endpoints is `/api/v1`.
|
- Base URL for v1 endpoints is `/api/v1`.
|
||||||
- Admin-only routes return `403 Forbidden` when the token user is not staff/superuser.
|
- Admin-only routes return `403 Forbidden` when the token user is not staff/superuser.
|
||||||
|
|
||||||
|
Example: update server display name (admin-only)
|
||||||
|
|
||||||
|
PATCH `/api/v1/servers/{server_id}`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"display_name": "Keywarden Prod"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|||||||
@@ -13,12 +13,17 @@ WORKDIR /app
|
|||||||
# System deps for psycopg2, node (for Tailwind), etc.
|
# System deps for psycopg2, node (for Tailwind), etc.
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
build-essential \
|
build-essential \
|
||||||
|
ca-certificates \
|
||||||
libpq-dev \
|
libpq-dev \
|
||||||
curl \
|
curl \
|
||||||
|
openssl \
|
||||||
nginx \
|
nginx \
|
||||||
nodejs \
|
nodejs \
|
||||||
npm \
|
npm \
|
||||||
supervisor \
|
supervisor \
|
||||||
|
mkcert \
|
||||||
|
libnss3-tools \
|
||||||
|
valkey-server \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# =============================================
|
# =============================================
|
||||||
@@ -44,7 +49,7 @@ RUN pip install --upgrade pip \
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY ./app .
|
COPY ./app .
|
||||||
|
|
||||||
COPY nginx/configs/nginx.conf /etc/nginx/nginx.conf
|
COPY nginx/configs/nginx.conf.template /etc/nginx/nginx.conf.template
|
||||||
COPY nginx/configs/options-* /etc/nginx/
|
COPY nginx/configs/options-* /etc/nginx/
|
||||||
#COPY nginx/configs/sites/ /etc/nginx/conf.d/
|
#COPY nginx/configs/sites/ /etc/nginx/conf.d/
|
||||||
COPY supervisor/supervisord.conf /etc/supervisor/supervisord.conf
|
COPY supervisor/supervisord.conf /etc/supervisor/supervisord.conf
|
||||||
|
|||||||
29
LICENSES/valkey.BSD-3-Clause.txt
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
BSD 3-Clause License
|
||||||
|
|
||||||
|
Copyright (c) 2024, Valkey contributors
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation
|
||||||
|
and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
3. Neither the name of the copyright holder nor the names of its
|
||||||
|
contributors may be used to endorse or promote products derived from
|
||||||
|
this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
22
THIRD_PARTY_NOTICES.md
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# Third-party notices
|
||||||
|
|
||||||
|
This project is licensed under the GNU AGPL v3. It includes third-party components that
|
||||||
|
are distributed under their own licenses. When redistributing Keywarden (source or binary),
|
||||||
|
ensure you comply with each component's license terms and include required notices.
|
||||||
|
|
||||||
|
## Valkey
|
||||||
|
Valkey is included in the container image and used as the cache backend.
|
||||||
|
License: BSD 3-Clause. See `LICENSES/valkey.BSD-3-Clause.txt`.
|
||||||
|
|
||||||
|
## Other third-party components
|
||||||
|
This repository and container image include additional dependencies (Python packages and
|
||||||
|
system packages). Their licenses typically require you to retain copyright notices and
|
||||||
|
license texts when redistributing binaries. Review the following sources to determine
|
||||||
|
exact obligations:
|
||||||
|
|
||||||
|
- `requirements.txt` for Python dependencies.
|
||||||
|
- `Dockerfile` for system packages installed into the image.
|
||||||
|
- `app/static/` and `app/theme/` for bundled frontend assets.
|
||||||
|
|
||||||
|
If you need a full license inventory, generate it from your build environment and add
|
||||||
|
corresponding license texts under `LICENSES/`.
|
||||||
1
agent/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
keywarden-agent
|
||||||
25
agent/README.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# keywarden-agent
|
||||||
|
|
||||||
|
Minimal Go agent scaffold for Keywarden.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```
|
||||||
|
go build -o keywarden-agent ./cmd/keywarden-agent
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```
|
||||||
|
./keywarden-agent -config /etc/keywarden/agent.json -server-url https://keywarden.example.com -enroll-token <token>
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also pass `KEYWARDEN_SERVER_URL` and `KEYWARDEN_ENROLL_TOKEN` as environment variables.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
On first boot, the agent will create a config file if it does not exist. Only `server_url` is required for bootstrapping.
|
||||||
|
|
||||||
|
If the Keywarden server uses a private TLS CA, set `server_ca_path` (or `KEYWARDEN_SERVER_CA_PATH`) to the CA PEM file so the agent can verify the server certificate.
|
||||||
|
|
||||||
|
See `config.example.json`.
|
||||||
273
agent/cmd/keywarden-agent/main.go
Normal file
@@ -0,0 +1,273 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/pem"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"keywarden/agent/internal/client"
|
||||||
|
"keywarden/agent/internal/config"
|
||||||
|
"keywarden/agent/internal/host"
|
||||||
|
"keywarden/agent/internal/logs"
|
||||||
|
"keywarden/agent/internal/version"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
configPath := flag.String("config", config.DefaultConfigPath, "Path to agent config JSON")
|
||||||
|
serverURL := flag.String("server-url", "", "Keywarden server URL (first boot)")
|
||||||
|
enrollToken := flag.String("enroll-token", "", "Enrollment token (first boot)")
|
||||||
|
showVersion := flag.Bool("version", false, "Print version and exit")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if *showVersion {
|
||||||
|
fmt.Printf("keywarden-agent %s (commit %s, built %s)\n", version.Version, version.Commit, version.BuildDate)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.LoadOrInit(*configPath, pickServerURL(*serverURL))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("config error: %v", err)
|
||||||
|
}
|
||||||
|
if err := ensureDirs(cfg); err != nil {
|
||||||
|
log.Fatalf("state dir error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := bootstrapIfNeeded(cfg, *configPath, pickEnrollToken(*enrollToken)); err != nil {
|
||||||
|
log.Fatalf("bootstrap error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
apiClient, err := client.New(cfg)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
interval := time.Duration(cfg.SyncIntervalSeconds) * time.Second
|
||||||
|
log.Printf("keywarden-agent started: server_id=%s interval=%s", cfg.ServerID, interval)
|
||||||
|
|
||||||
|
ticker := time.NewTicker(interval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
runOnce(ctx, apiClient, cfg)
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Printf("shutdown requested")
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
runOnce(ctx, apiClient, cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runOnce(ctx context.Context, apiClient *client.Client, cfg *config.Config) {
|
||||||
|
if err := reportHost(ctx, apiClient, cfg); err != nil {
|
||||||
|
if client.IsRetriable(err) {
|
||||||
|
log.Printf("host update deferred; will retry: %v", err)
|
||||||
|
} else {
|
||||||
|
log.Printf("host update error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := apiClient.SyncAccounts(ctx, cfg); err != nil {
|
||||||
|
log.Printf("sync accounts error: %v", err)
|
||||||
|
}
|
||||||
|
if err := shipLogs(ctx, apiClient, cfg); err != nil {
|
||||||
|
if client.IsRetriable(err) {
|
||||||
|
log.Printf("log shipping deferred; will retry: %v", err)
|
||||||
|
} else {
|
||||||
|
log.Printf("log shipping error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureDirs(cfg *config.Config) error {
|
||||||
|
if err := os.MkdirAll(cfg.StateDir, 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(cfg.LogSpoolDir(), 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func shipLogs(ctx context.Context, apiClient *client.Client, cfg *config.Config) error {
|
||||||
|
send := func(payload []byte) error {
|
||||||
|
return retry(ctx, []time.Duration{250 * time.Millisecond, time.Second, 2 * time.Second}, func() error {
|
||||||
|
return apiClient.SendLogBatch(ctx, cfg.ServerID, payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if err := logs.DrainSpool(cfg.LogSpoolDir(), send); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor, err := logs.ReadCursor(cfg.LogCursorPath())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
collector := logs.NewCollector()
|
||||||
|
events, nextCursor, err := collector.Collect(ctx, cursor, cfg.LogBatchSize)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(events) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
payload, err := json.Marshal(events)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := send(payload); err != nil {
|
||||||
|
if spoolErr := logs.SaveSpool(cfg.LogSpoolDir(), payload); spoolErr != nil {
|
||||||
|
return spoolErr
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := logs.WriteCursor(cfg.LogCursorPath(), nextCursor); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func reportHost(ctx context.Context, apiClient *client.Client, cfg *config.Config) error {
|
||||||
|
info := host.Detect()
|
||||||
|
return retry(ctx, []time.Duration{250 * time.Millisecond, time.Second, 2 * time.Second}, func() error {
|
||||||
|
return apiClient.UpdateHost(ctx, cfg.ServerID, client.HeartbeatRequest{
|
||||||
|
Host: info.Hostname,
|
||||||
|
IPv4: info.IPv4,
|
||||||
|
IPv6: info.IPv6,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func pickServerURL(flagValue string) string {
|
||||||
|
if flagValue != "" {
|
||||||
|
return flagValue
|
||||||
|
}
|
||||||
|
return os.Getenv("KEYWARDEN_SERVER_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
func pickEnrollToken(flagValue string) string {
|
||||||
|
if flagValue != "" {
|
||||||
|
return flagValue
|
||||||
|
}
|
||||||
|
return os.Getenv("KEYWARDEN_ENROLL_TOKEN")
|
||||||
|
}
|
||||||
|
|
||||||
|
func bootstrapIfNeeded(cfg *config.Config, configPath string, enrollToken string) error {
|
||||||
|
if cfg.ServerID != "" && fileExists(cfg.ClientCertPath()) && fileExists(cfg.CACertPath()) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if enrollToken == "" {
|
||||||
|
return fmt.Errorf("missing enrollment token; set KEYWARDEN_ENROLL_TOKEN or -enroll-token")
|
||||||
|
}
|
||||||
|
keyPath := cfg.ClientKeyPath()
|
||||||
|
if !fileExists(keyPath) {
|
||||||
|
if err := generateKey(keyPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
csrPEM, err := buildCSR(keyPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
info := host.Detect()
|
||||||
|
hostname := info.Hostname
|
||||||
|
resp, err := client.Enroll(context.Background(), cfg.ServerURL, client.EnrollRequest{
|
||||||
|
Token: enrollToken,
|
||||||
|
CSRPEM: csrPEM,
|
||||||
|
Host: hostname,
|
||||||
|
IPv4: info.IPv4,
|
||||||
|
IPv6: info.IPv6,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(cfg.ClientCertPath(), []byte(resp.ClientCert), 0o600); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(cfg.CACertPath(), []byte(resp.CACert), 0o600); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cfg.ServerID = resp.ServerID
|
||||||
|
if err := config.Save(configPath, cfg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func retry(ctx context.Context, delays []time.Duration, fn func() error) error {
|
||||||
|
var lastErr error
|
||||||
|
for attempt := 0; attempt <= len(delays); attempt++ {
|
||||||
|
if attempt > 0 {
|
||||||
|
if !client.IsRetriable(lastErr) {
|
||||||
|
return lastErr
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-time.After(delays[attempt-1]):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := fn(); err != nil {
|
||||||
|
lastErr = err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return lastErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateKey(path string) error {
|
||||||
|
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
keyDER := x509.MarshalPKCS1PrivateKey(key)
|
||||||
|
block := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyDER}
|
||||||
|
data := pem.EncodeToMemory(block)
|
||||||
|
return os.WriteFile(path, data, 0o600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildCSR(keyPath string) (string, error) {
|
||||||
|
keyData, err := os.ReadFile(keyPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
block, _ := pem.Decode(keyData)
|
||||||
|
if block == nil || block.Type != "RSA PRIVATE KEY" {
|
||||||
|
return "", fmt.Errorf("invalid private key")
|
||||||
|
}
|
||||||
|
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
csrTemplate := &x509.CertificateRequest{Subject: pkix.Name{CommonName: "keywarden-agent"}}
|
||||||
|
csrDER, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, key)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
csrBlock := &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}
|
||||||
|
return string(pem.EncodeToMemory(csrBlock)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileExists(path string) bool {
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return !info.IsDir()
|
||||||
|
}
|
||||||
15
agent/config.example.json
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"server_url": "https://keywarden.dev.ntbx.io/api/v1",
|
||||||
|
"server_id": "4",
|
||||||
|
"server_ca_path": "",
|
||||||
|
"sync_interval_seconds": 30,
|
||||||
|
"log_batch_size": 500,
|
||||||
|
"state_dir": "/var/lib/keywarden-agent",
|
||||||
|
"account_policy": {
|
||||||
|
"username_template": "{{username}}_{{user_id}}",
|
||||||
|
"default_shell": "/bin/bash",
|
||||||
|
"admin_group": "sudo",
|
||||||
|
"create_home": true,
|
||||||
|
"lock_on_revoke": true
|
||||||
|
}
|
||||||
|
}
|
||||||
7
agent/go.mod
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
module keywarden/agent
|
||||||
|
|
||||||
|
go 1.22
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/coreos/go-systemd/v22 v22.5.0
|
||||||
|
)
|
||||||
3
agent/go.sum
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
|
||||||
|
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||||
|
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
323
agent/internal/accounts/sync.go
Normal file
@@ -0,0 +1,323 @@
|
|||||||
|
package accounts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"keywarden/agent/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
stateFileName = "accounts.json"
|
||||||
|
maxUsernameLen = 32
|
||||||
|
passwdFilePath = "/etc/passwd"
|
||||||
|
sshDirName = ".ssh"
|
||||||
|
authKeysName = "authorized_keys"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AccessUser struct {
|
||||||
|
UserID int
|
||||||
|
Username string
|
||||||
|
Email string
|
||||||
|
Keys []string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReportAccount struct {
|
||||||
|
UserID int `json:"user_id"`
|
||||||
|
SystemUser string `json:"system_username"`
|
||||||
|
Present bool `json:"present"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Applied int
|
||||||
|
Revoked int
|
||||||
|
Accounts []ReportAccount
|
||||||
|
}
|
||||||
|
|
||||||
|
type managedAccount struct {
|
||||||
|
UserID int `json:"user_id"`
|
||||||
|
SystemUser string `json:"system_username"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type state struct {
|
||||||
|
Users map[string]managedAccount `json:"users"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type passwdEntry struct {
|
||||||
|
UID int
|
||||||
|
GID int
|
||||||
|
Home string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Sync(policy config.AccountPolicy, stateDir string, users []AccessUser) (Result, error) {
|
||||||
|
result := Result{}
|
||||||
|
statePath := filepath.Join(stateDir, stateFileName)
|
||||||
|
current, err := loadState(statePath)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
desired := make(map[int]managedAccount, len(users))
|
||||||
|
userIndex := make(map[int]AccessUser, len(users))
|
||||||
|
for _, user := range users {
|
||||||
|
systemUser := renderUsername(policy.UsernameTemplate, user.Username, user.UserID)
|
||||||
|
desired[user.UserID] = managedAccount{UserID: user.UserID, SystemUser: systemUser}
|
||||||
|
userIndex[user.UserID] = user
|
||||||
|
}
|
||||||
|
|
||||||
|
var syncErr error
|
||||||
|
for _, account := range current.Users {
|
||||||
|
if _, ok := desired[account.UserID]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := revokeUser(account.SystemUser, policy); err != nil && syncErr == nil {
|
||||||
|
syncErr = err
|
||||||
|
}
|
||||||
|
result.Revoked++
|
||||||
|
}
|
||||||
|
|
||||||
|
for userID, account := range desired {
|
||||||
|
accessUser := userIndex[userID]
|
||||||
|
present, err := ensureAccount(account.SystemUser, policy, accessUser.Keys)
|
||||||
|
if err != nil && syncErr == nil {
|
||||||
|
syncErr = err
|
||||||
|
}
|
||||||
|
if present {
|
||||||
|
result.Applied++
|
||||||
|
}
|
||||||
|
result.Accounts = append(result.Accounts, ReportAccount{
|
||||||
|
UserID: userID,
|
||||||
|
SystemUser: account.SystemUser,
|
||||||
|
Present: present,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := saveState(statePath, desired); err != nil && syncErr == nil {
|
||||||
|
syncErr = err
|
||||||
|
}
|
||||||
|
return result, syncErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadState(path string) (state, error) {
|
||||||
|
st := state{Users: map[string]managedAccount{}}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
return st, fmt.Errorf("read state: %w", err)
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(data, &st); err != nil {
|
||||||
|
return st, fmt.Errorf("parse state: %w", err)
|
||||||
|
}
|
||||||
|
if st.Users == nil {
|
||||||
|
st.Users = map[string]managedAccount{}
|
||||||
|
}
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveState(path string, desired map[int]managedAccount) error {
|
||||||
|
st := state{Users: map[string]managedAccount{}}
|
||||||
|
for id, account := range desired {
|
||||||
|
st.Users[strconv.Itoa(id)] = account
|
||||||
|
}
|
||||||
|
data, err := json.MarshalIndent(st, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode state: %w", err)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
return fmt.Errorf("create state dir: %w", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||||
|
return fmt.Errorf("write state: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderUsername(template string, username string, userID int) string {
|
||||||
|
raw := strings.ReplaceAll(template, "{{username}}", username)
|
||||||
|
raw = strings.ReplaceAll(raw, "{{user_id}}", strconv.Itoa(userID))
|
||||||
|
clean := sanitizeUsername(raw)
|
||||||
|
if len(clean) > maxUsernameLen {
|
||||||
|
clean = clean[:maxUsernameLen]
|
||||||
|
}
|
||||||
|
if clean == "" {
|
||||||
|
clean = fmt.Sprintf("kw_%d", userID)
|
||||||
|
}
|
||||||
|
return clean
|
||||||
|
}
|
||||||
|
|
||||||
|
func sanitizeUsername(raw string) string {
|
||||||
|
raw = strings.ToLower(raw)
|
||||||
|
var b strings.Builder
|
||||||
|
b.Grow(len(raw))
|
||||||
|
for _, r := range raw {
|
||||||
|
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' {
|
||||||
|
b.WriteRune(r)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.WriteByte('_')
|
||||||
|
}
|
||||||
|
out := strings.Trim(b.String(), "-_")
|
||||||
|
if out == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(out, "-") {
|
||||||
|
return "kw" + out
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func userExists(username string) (bool, error) {
|
||||||
|
cmd := exec.Command("id", "-u", username)
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
if _, ok := err.(*exec.ExitError); ok {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureAccount(username string, policy config.AccountPolicy, keys []string) (bool, error) {
|
||||||
|
exists, err := userExists(username)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
if err := createUser(username, policy); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := lockPassword(username); err != nil {
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
if err := writeAuthorizedKeys(username, keys); err != nil {
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func createUser(username string, policy config.AccountPolicy) error {
|
||||||
|
args := []string{"-U"}
|
||||||
|
if policy.CreateHome {
|
||||||
|
args = append(args, "-m")
|
||||||
|
} else {
|
||||||
|
args = append(args, "-M")
|
||||||
|
}
|
||||||
|
if policy.DefaultShell != "" {
|
||||||
|
args = append(args, "-s", policy.DefaultShell)
|
||||||
|
}
|
||||||
|
args = append(args, username)
|
||||||
|
cmd := exec.Command("useradd", args...)
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
return fmt.Errorf("useradd %s: %w", username, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lockPassword(username string) error {
|
||||||
|
cmd := exec.Command("usermod", "-L", username)
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
return fmt.Errorf("lock password %s: %w", username, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func revokeUser(username string, policy config.AccountPolicy) error {
|
||||||
|
exists, err := userExists(username)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var revokeErr error
|
||||||
|
if policy.LockOnRevoke {
|
||||||
|
if err := lockPassword(username); err != nil {
|
||||||
|
revokeErr = err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := writeAuthorizedKeys(username, nil); err != nil && revokeErr == nil {
|
||||||
|
revokeErr = err
|
||||||
|
}
|
||||||
|
return revokeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAuthorizedKeys(username string, keys []string) error {
|
||||||
|
entry, err := lookupUser(username)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if entry.Home == "" {
|
||||||
|
return fmt.Errorf("missing home dir for %s", username)
|
||||||
|
}
|
||||||
|
sshDir := filepath.Join(entry.Home, sshDirName)
|
||||||
|
if err := os.MkdirAll(sshDir, 0o700); err != nil {
|
||||||
|
return fmt.Errorf("mkdir %s: %w", sshDir, err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(sshDir, 0o700); err != nil {
|
||||||
|
return fmt.Errorf("chmod %s: %w", sshDir, err)
|
||||||
|
}
|
||||||
|
if err := os.Chown(sshDir, entry.UID, entry.GID); err != nil {
|
||||||
|
return fmt.Errorf("chown %s: %w", sshDir, err)
|
||||||
|
}
|
||||||
|
authKeysPath := filepath.Join(sshDir, authKeysName)
|
||||||
|
payload := strings.TrimSpace(strings.Join(keys, "\n"))
|
||||||
|
if payload != "" {
|
||||||
|
payload += "\n"
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(authKeysPath, []byte(payload), 0o600); err != nil {
|
||||||
|
return fmt.Errorf("write %s: %w", authKeysPath, err)
|
||||||
|
}
|
||||||
|
if err := os.Chown(authKeysPath, entry.UID, entry.GID); err != nil {
|
||||||
|
return fmt.Errorf("chown %s: %w", authKeysPath, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupUser(username string) (passwdEntry, error) {
|
||||||
|
file, err := os.Open(passwdFilePath)
|
||||||
|
if err != nil {
|
||||||
|
return passwdEntry{}, fmt.Errorf("open passwd: %w", err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
scanner := bufio.NewScanner(file)
|
||||||
|
for scanner.Scan() {
|
||||||
|
line := scanner.Text()
|
||||||
|
if line == "" || strings.HasPrefix(line, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fields := strings.SplitN(line, ":", 7)
|
||||||
|
if len(fields) < 7 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fields[0] != username {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
uid, err := strconv.Atoi(fields[2])
|
||||||
|
if err != nil {
|
||||||
|
return passwdEntry{}, fmt.Errorf("parse uid for %s: %w", username, err)
|
||||||
|
}
|
||||||
|
gid, err := strconv.Atoi(fields[3])
|
||||||
|
if err != nil {
|
||||||
|
return passwdEntry{}, fmt.Errorf("parse gid for %s: %w", username, err)
|
||||||
|
}
|
||||||
|
return passwdEntry{
|
||||||
|
UID: uid,
|
||||||
|
GID: gid,
|
||||||
|
Home: fields[5],
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
if err := scanner.Err(); err != nil {
|
||||||
|
return passwdEntry{}, fmt.Errorf("scan passwd: %w", err)
|
||||||
|
}
|
||||||
|
return passwdEntry{}, fmt.Errorf("user %s not found", username)
|
||||||
|
}
|
||||||
286
agent/internal/client/client.go
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"keywarden/agent/internal/accounts"
|
||||||
|
"keywarden/agent/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
const defaultTimeout = 15 * time.Second
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
baseURL string
|
||||||
|
http *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(cfg *config.Config) (*Client, error) {
|
||||||
|
baseURL := strings.TrimRight(cfg.ServerURL, "/")
|
||||||
|
if baseURL == "" {
|
||||||
|
return nil, errors.New("server url is required")
|
||||||
|
}
|
||||||
|
cert, err := tls.LoadX509KeyPair(cfg.ClientCertPath(), cfg.ClientKeyPath())
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("load client cert: %w", err)
|
||||||
|
}
|
||||||
|
caPool, err := x509.SystemCertPool()
|
||||||
|
if err != nil || caPool == nil {
|
||||||
|
caPool = x509.NewCertPool()
|
||||||
|
}
|
||||||
|
if cfg.ServerCAPath != "" {
|
||||||
|
caData, err := os.ReadFile(cfg.ServerCAPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read server ca cert: %w", err)
|
||||||
|
}
|
||||||
|
if !caPool.AppendCertsFromPEM(caData) {
|
||||||
|
return nil, errors.New("parse server ca cert")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
Certificates: []tls.Certificate{cert},
|
||||||
|
RootCAs: caPool,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
}
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
TLSClientConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
httpClient := &http.Client{
|
||||||
|
Timeout: defaultTimeout,
|
||||||
|
Transport: transport,
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Client{baseURL: baseURL, http: httpClient}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type EnrollRequest struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
CSRPEM string `json:"csr_pem"`
|
||||||
|
Host string `json:"host"`
|
||||||
|
IPv4 string `json:"ipv4,omitempty"`
|
||||||
|
IPv6 string `json:"ipv6,omitempty"`
|
||||||
|
AgentID string `json:"agent_id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type EnrollResponse struct {
|
||||||
|
ServerID string `json:"server_id"`
|
||||||
|
ClientCert string `json:"client_cert_pem"`
|
||||||
|
CACert string `json:"ca_cert_pem"`
|
||||||
|
SyncProfile string `json:"sync_profile,omitempty"`
|
||||||
|
DisplayName string `json:"display_name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AccountKey struct {
|
||||||
|
PublicKey string `json:"public_key"`
|
||||||
|
Fingerprint string `json:"fingerprint"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AccountAccess struct {
|
||||||
|
UserID int `json:"user_id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Keys []AccountKey `json:"keys"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AccountSyncEntry struct {
|
||||||
|
UserID int `json:"user_id"`
|
||||||
|
SystemUsername string `json:"system_username"`
|
||||||
|
Present bool `json:"present"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SyncReportRequest struct {
|
||||||
|
AppliedCount int `json:"applied_count"`
|
||||||
|
RevokedCount int `json:"revoked_count"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Metadata map[string]any `json:"metadata,omitempty"`
|
||||||
|
Accounts []AccountSyncEntry `json:"accounts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Enroll(ctx context.Context, serverURL string, req EnrollRequest) (*EnrollResponse, error) {
|
||||||
|
baseURL := strings.TrimRight(serverURL, "/")
|
||||||
|
if baseURL == "" {
|
||||||
|
return nil, errors.New("server url is required")
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("encode enroll request: %w", err)
|
||||||
|
}
|
||||||
|
httpClient := &http.Client{Timeout: defaultTimeout}
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+"/agent/enroll", bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("build enroll request: %w", err)
|
||||||
|
}
|
||||||
|
httpReq.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("enroll request: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("enroll failed: status %s", resp.Status)
|
||||||
|
}
|
||||||
|
var out EnrollResponse
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||||
|
return nil, fmt.Errorf("decode enroll response: %w", err)
|
||||||
|
}
|
||||||
|
if out.ServerID == "" || out.ClientCert == "" || out.CACert == "" {
|
||||||
|
return nil, errors.New("enroll response missing required fields")
|
||||||
|
}
|
||||||
|
return &out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) SyncAccounts(ctx context.Context, cfg *config.Config) error {
|
||||||
|
if cfg == nil {
|
||||||
|
return errors.New("config required for account sync")
|
||||||
|
}
|
||||||
|
users, err := c.FetchAccountAccess(ctx, cfg.ServerID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
accessUsers := make([]accounts.AccessUser, 0, len(users))
|
||||||
|
for _, user := range users {
|
||||||
|
keys := make([]string, 0, len(user.Keys))
|
||||||
|
for _, key := range user.Keys {
|
||||||
|
if strings.TrimSpace(key.PublicKey) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
keys = append(keys, strings.TrimSpace(key.PublicKey))
|
||||||
|
}
|
||||||
|
accessUsers = append(accessUsers, accounts.AccessUser{
|
||||||
|
UserID: user.UserID,
|
||||||
|
Username: user.Username,
|
||||||
|
Email: user.Email,
|
||||||
|
Keys: keys,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
result, syncErr := accounts.Sync(cfg.AccountPolicy, cfg.StateDir, accessUsers)
|
||||||
|
report := SyncReportRequest{
|
||||||
|
AppliedCount: result.Applied,
|
||||||
|
RevokedCount: result.Revoked,
|
||||||
|
Accounts: make([]AccountSyncEntry, 0, len(result.Accounts)),
|
||||||
|
}
|
||||||
|
for _, account := range result.Accounts {
|
||||||
|
report.Accounts = append(report.Accounts, AccountSyncEntry{
|
||||||
|
UserID: account.UserID,
|
||||||
|
SystemUsername: account.SystemUser,
|
||||||
|
Present: account.Present,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if syncErr != nil {
|
||||||
|
report.Message = syncErr.Error()
|
||||||
|
}
|
||||||
|
if err := c.SendSyncReport(ctx, cfg.ServerID, report); err != nil {
|
||||||
|
if syncErr != nil {
|
||||||
|
return fmt.Errorf("sync report failed: %w (sync error: %v)", err, syncErr)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return syncErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) FetchAccountAccess(ctx context.Context, serverID string) ([]AccountAccess, error) {
|
||||||
|
req, err := http.NewRequestWithContext(
|
||||||
|
ctx,
|
||||||
|
http.MethodGet,
|
||||||
|
c.baseURL+"/agent/servers/"+serverID+"/accounts",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("build account access request: %w", err)
|
||||||
|
}
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fetch account access: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Status: resp.Status}
|
||||||
|
}
|
||||||
|
var out []AccountAccess
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||||
|
return nil, fmt.Errorf("decode account access: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) SendSyncReport(ctx context.Context, serverID string, report SyncReportRequest) error {
|
||||||
|
body, err := json.Marshal(report)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode sync report: %w", err)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(
|
||||||
|
ctx,
|
||||||
|
http.MethodPost,
|
||||||
|
c.baseURL+"/agent/servers/"+serverID+"/sync-report",
|
||||||
|
bytes.NewReader(body),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("build sync report: %w", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("send sync report: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
return &HTTPStatusError{StatusCode: resp.StatusCode, Status: resp.Status}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) SendLogBatch(ctx context.Context, serverID string, payload []byte) error {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/agent/servers/"+serverID+"/logs", bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("build log request: %w", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("send log batch: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
return &HTTPStatusError{StatusCode: resp.StatusCode, Status: resp.Status}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type HeartbeatRequest struct {
|
||||||
|
Host string `json:"host,omitempty"`
|
||||||
|
IPv4 string `json:"ipv4,omitempty"`
|
||||||
|
IPv6 string `json:"ipv6,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) UpdateHost(ctx context.Context, serverID string, reqBody HeartbeatRequest) error {
|
||||||
|
body, err := json.Marshal(reqBody)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode host update: %w", err)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/agent/servers/"+serverID+"/heartbeat", bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("build host update: %w", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("send host update: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
return &HTTPStatusError{StatusCode: resp.StatusCode, Status: resp.Status}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
36
agent/internal/client/errors.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HTTPStatusError struct {
|
||||||
|
StatusCode int
|
||||||
|
Status string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *HTTPStatusError) Error() string {
|
||||||
|
return "remote status " + e.Status
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsRetriable(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var statusErr *HTTPStatusError
|
||||||
|
if errors.As(err, &statusErr) {
|
||||||
|
switch statusErr.StatusCode {
|
||||||
|
case 404, 408, 429, 500, 502, 503, 504:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
var netErr net.Error
|
||||||
|
return errors.As(err, &netErr)
|
||||||
|
}
|
||||||
152
agent/internal/config/config.go
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultConfigPath = "/etc/keywarden/agent.json"
|
||||||
|
DefaultStateDir = "/var/lib/keywarden-agent"
|
||||||
|
DefaultSyncIntervalSeconds = 30
|
||||||
|
DefaultLogBatchSize = 500
|
||||||
|
DefaultUsernameTemplate = "{{username}}_{{user_id}}"
|
||||||
|
DefaultShell = "/bin/bash"
|
||||||
|
DefaultAdminGroup = "sudo"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AccountPolicy struct {
|
||||||
|
UsernameTemplate string `json:"username_template"`
|
||||||
|
DefaultShell string `json:"default_shell"`
|
||||||
|
AdminGroup string `json:"admin_group"`
|
||||||
|
CreateHome bool `json:"create_home"`
|
||||||
|
LockOnRevoke bool `json:"lock_on_revoke"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
ServerURL string `json:"server_url"`
|
||||||
|
ServerID string `json:"server_id,omitempty"`
|
||||||
|
ServerCAPath string `json:"server_ca_path,omitempty"`
|
||||||
|
SyncIntervalSeconds int `json:"sync_interval_seconds,omitempty"`
|
||||||
|
LogBatchSize int `json:"log_batch_size,omitempty"`
|
||||||
|
StateDir string `json:"state_dir,omitempty"`
|
||||||
|
AccountPolicy AccountPolicy `json:"account_policy,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadOrInit(path string, serverURL string) (*Config, error) {
|
||||||
|
if path == "" {
|
||||||
|
path = DefaultConfigPath
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, fmt.Errorf("read config: %w", err)
|
||||||
|
}
|
||||||
|
if serverURL == "" {
|
||||||
|
return nil, errors.New("server url required for first boot")
|
||||||
|
}
|
||||||
|
cfg := &Config{ServerURL: serverURL, ServerCAPath: os.Getenv("KEYWARDEN_SERVER_CA_PATH")}
|
||||||
|
applyDefaults(cfg)
|
||||||
|
if err := validate(cfg, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := Save(path, cfg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
cfg := &Config{}
|
||||||
|
if err := json.Unmarshal(data, cfg); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse config: %w", err)
|
||||||
|
}
|
||||||
|
if cfg.ServerCAPath == "" {
|
||||||
|
cfg.ServerCAPath = os.Getenv("KEYWARDEN_SERVER_CA_PATH")
|
||||||
|
}
|
||||||
|
applyDefaults(cfg)
|
||||||
|
if err := validate(cfg, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Save(path string, cfg *Config) error {
|
||||||
|
data, err := json.MarshalIndent(cfg, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode config: %w", err)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(dir(path), 0o755); err != nil {
|
||||||
|
return fmt.Errorf("create config dir: %w", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||||
|
return fmt.Errorf("write config: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyDefaults(cfg *Config) {
|
||||||
|
if cfg.SyncIntervalSeconds <= 0 {
|
||||||
|
cfg.SyncIntervalSeconds = DefaultSyncIntervalSeconds
|
||||||
|
}
|
||||||
|
if cfg.LogBatchSize <= 0 {
|
||||||
|
cfg.LogBatchSize = DefaultLogBatchSize
|
||||||
|
}
|
||||||
|
if cfg.StateDir == "" {
|
||||||
|
cfg.StateDir = DefaultStateDir
|
||||||
|
}
|
||||||
|
if cfg.AccountPolicy.UsernameTemplate == "" {
|
||||||
|
cfg.AccountPolicy.UsernameTemplate = DefaultUsernameTemplate
|
||||||
|
}
|
||||||
|
if cfg.AccountPolicy.DefaultShell == "" {
|
||||||
|
cfg.AccountPolicy.DefaultShell = DefaultShell
|
||||||
|
}
|
||||||
|
if cfg.AccountPolicy.AdminGroup == "" {
|
||||||
|
cfg.AccountPolicy.AdminGroup = DefaultAdminGroup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validate(cfg *Config, requireServerID bool) error {
|
||||||
|
var missing []string
|
||||||
|
if cfg.ServerURL == "" {
|
||||||
|
missing = append(missing, "server_url")
|
||||||
|
}
|
||||||
|
if requireServerID && cfg.ServerID == "" {
|
||||||
|
missing = append(missing, "server_id")
|
||||||
|
}
|
||||||
|
if len(missing) > 0 {
|
||||||
|
return fmt.Errorf("missing required config fields: %v", missing)
|
||||||
|
}
|
||||||
|
if cfg.SyncIntervalSeconds < 5 {
|
||||||
|
return errors.New("sync_interval_seconds must be >= 5")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) ClientCertPath() string {
|
||||||
|
return c.StateDir + "/agent.crt"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) ClientKeyPath() string {
|
||||||
|
return c.StateDir + "/agent.key"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) CACertPath() string {
|
||||||
|
return c.StateDir + "/ca.crt"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) LogCursorPath() string {
|
||||||
|
return c.StateDir + "/journal.cursor"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) LogSpoolDir() string {
|
||||||
|
return c.StateDir + "/spool"
|
||||||
|
}
|
||||||
|
|
||||||
|
func dir(path string) string {
|
||||||
|
if idx := strings.LastIndex(path, string(os.PathSeparator)); idx != -1 {
|
||||||
|
return path[:idx]
|
||||||
|
}
|
||||||
|
return "."
|
||||||
|
}
|
||||||
57
agent/internal/host/host.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package host
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Info struct {
|
||||||
|
Hostname string
|
||||||
|
IPv4 string
|
||||||
|
IPv6 string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Detect() Info {
|
||||||
|
hostname, _ := os.Hostname()
|
||||||
|
info := Info{Hostname: hostname}
|
||||||
|
ifaces, err := net.Interfaces()
|
||||||
|
if err != nil {
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
for _, iface := range ifaces {
|
||||||
|
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addrs, err := iface.Addrs()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, addr := range addrs {
|
||||||
|
var ip net.IP
|
||||||
|
switch v := addr.(type) {
|
||||||
|
case *net.IPNet:
|
||||||
|
ip = v.IP
|
||||||
|
case *net.IPAddr:
|
||||||
|
ip = v.IP
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip == nil || ip.IsLoopback() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip4 := ip.To4(); ip4 != nil {
|
||||||
|
if info.IPv4 == "" {
|
||||||
|
info.IPv4 = ip4.String()
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip.To16() != nil && info.IPv6 == "" {
|
||||||
|
info.IPv6 = ip.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if info.IPv4 != "" && info.IPv6 != "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return info
|
||||||
|
}
|
||||||
177
agent/internal/logs/collector.go
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
package logs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/coreos/go-systemd/v22/sdjournal"
|
||||||
|
)
|
||||||
|
|
||||||
|
const defaultLimit = 500
|
||||||
|
|
||||||
|
type Collector struct {
|
||||||
|
matches []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCollector() *Collector {
|
||||||
|
return &Collector{matches: defaultMatches()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Collector) Collect(ctx context.Context, cursor string, limit int) ([]Event, string, error) {
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = defaultLimit
|
||||||
|
}
|
||||||
|
j, err := sdjournal.NewJournal()
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
defer j.Close()
|
||||||
|
|
||||||
|
for i, match := range c.matches {
|
||||||
|
if i > 0 {
|
||||||
|
if err := j.AddDisjunction(); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := j.AddMatch(match); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if cursor != "" {
|
||||||
|
if err := j.SeekCursor(cursor); err == nil {
|
||||||
|
_, _ = j.Next()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_ = j.SeekTail()
|
||||||
|
_, _ = j.Next()
|
||||||
|
}
|
||||||
|
|
||||||
|
var events []Event
|
||||||
|
var nextCursor string
|
||||||
|
for len(events) < limit {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return events, nextCursor, ctx.Err()
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
n, err := j.Next()
|
||||||
|
if err != nil {
|
||||||
|
return events, nextCursor, err
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
entry, err := j.GetEntry()
|
||||||
|
if err != nil {
|
||||||
|
return events, nextCursor, err
|
||||||
|
}
|
||||||
|
event := fromEntry(entry)
|
||||||
|
events = append(events, event)
|
||||||
|
nextCursor = entry.Cursor
|
||||||
|
}
|
||||||
|
|
||||||
|
return events, nextCursor, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultMatches() []string {
|
||||||
|
return []string{
|
||||||
|
"_SYSTEMD_UNIT=sshd.service",
|
||||||
|
"_SYSTEMD_UNIT=sudo.service",
|
||||||
|
"_SYSTEMD_UNIT=systemd-networkd.service",
|
||||||
|
"_SYSTEMD_UNIT=NetworkManager.service",
|
||||||
|
"_SYSTEMD_UNIT=systemd-logind.service",
|
||||||
|
"_TRANSPORT=kernel",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func fromEntry(entry *sdjournal.JournalEntry) Event {
|
||||||
|
ts := time.Unix(0, int64(entry.RealtimeTimestamp)*int64(time.Microsecond))
|
||||||
|
event := NewEvent(ts)
|
||||||
|
fields := entry.Fields
|
||||||
|
unit := fields["_SYSTEMD_UNIT"]
|
||||||
|
message := fields["MESSAGE"]
|
||||||
|
identifier := fields["SYSLOG_IDENTIFIER"]
|
||||||
|
|
||||||
|
event.Unit = unit
|
||||||
|
event.Message = message
|
||||||
|
event.Priority = fields["PRIORITY"]
|
||||||
|
event.Hostname = fields["_HOSTNAME"]
|
||||||
|
event.Fields = fields
|
||||||
|
|
||||||
|
event.Category = categorize(unit, identifier, fields)
|
||||||
|
event.EventType, event.Username, event.SourceIP, event.SessionID = parseMessage(event.Category, message)
|
||||||
|
if event.EventType == "" {
|
||||||
|
event.EventType = defaultEventType(event.Category)
|
||||||
|
}
|
||||||
|
return event
|
||||||
|
}
|
||||||
|
|
||||||
|
func categorize(unit string, identifier string, fields map[string]string) string {
|
||||||
|
switch {
|
||||||
|
case unit == "sshd.service" || identifier == "sshd":
|
||||||
|
return "access"
|
||||||
|
case unit == "sudo.service" || identifier == "sudo":
|
||||||
|
return "auth"
|
||||||
|
case unit == "systemd-networkd.service" || identifier == "NetworkManager":
|
||||||
|
return "network"
|
||||||
|
case fields["_TRANSPORT"] == "kernel":
|
||||||
|
return "system"
|
||||||
|
default:
|
||||||
|
return "system"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultEventType(category string) string {
|
||||||
|
switch category {
|
||||||
|
case "access":
|
||||||
|
return "ssh"
|
||||||
|
case "auth":
|
||||||
|
return "auth"
|
||||||
|
case "network":
|
||||||
|
return "network"
|
||||||
|
default:
|
||||||
|
return "system"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseMessage(category string, msg string) (eventType string, username string, sourceIP string, sessionID string) {
|
||||||
|
if msg == "" {
|
||||||
|
return "", "", "", ""
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(msg)
|
||||||
|
if category == "access" {
|
||||||
|
switch {
|
||||||
|
case strings.Contains(lower, "accepted"):
|
||||||
|
eventType = "ssh.login.success"
|
||||||
|
username = extractBetween(msg, "for ", " from")
|
||||||
|
sourceIP = extractBetween(msg, "from ", " port")
|
||||||
|
case strings.Contains(lower, "failed password"):
|
||||||
|
eventType = "ssh.login.fail"
|
||||||
|
username = extractBetween(msg, "for ", " from")
|
||||||
|
sourceIP = extractBetween(msg, "from ", " port")
|
||||||
|
case strings.Contains(lower, "session opened"):
|
||||||
|
eventType = "ssh.session.open"
|
||||||
|
username = extractBetween(msg, "for user ", " by")
|
||||||
|
case strings.Contains(lower, "session closed"):
|
||||||
|
eventType = "ssh.session.close"
|
||||||
|
username = extractBetween(msg, "for user ", " by")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return eventType, strings.TrimSpace(username), strings.TrimSpace(sourceIP), strings.TrimSpace(sessionID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractBetween(msg string, start string, end string) string {
|
||||||
|
startIdx := strings.Index(msg, start)
|
||||||
|
if startIdx == -1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
startIdx += len(start)
|
||||||
|
rest := msg[startIdx:]
|
||||||
|
endIdx := strings.Index(rest, end)
|
||||||
|
if endIdx == -1 {
|
||||||
|
return strings.TrimSpace(rest)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(rest[:endIdx])
|
||||||
|
}
|
||||||
24
agent/internal/logs/cursor.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package logs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ReadCursor(path string) (string, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(data)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteCursor(path string, cursor string) error {
|
||||||
|
if cursor == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return os.WriteFile(path, []byte(cursor+"\n"), 0o600)
|
||||||
|
}
|
||||||
53
agent/internal/logs/spool.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package logs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SaveSpool(dir string, payload []byte) error {
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
name := fmt.Sprintf("%d.json", time.Now().UnixNano())
|
||||||
|
tmp := filepath.Join(dir, name+".tmp")
|
||||||
|
final := filepath.Join(dir, name)
|
||||||
|
if err := os.WriteFile(tmp, payload, 0o600); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, final)
|
||||||
|
}
|
||||||
|
|
||||||
|
func DrainSpool(dir string, send func([]byte) error) error {
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var files []string
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
files = append(files, filepath.Join(dir, entry.Name()))
|
||||||
|
}
|
||||||
|
sort.Strings(files)
|
||||||
|
for _, path := range files {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := send(data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Remove(path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
23
agent/internal/logs/types.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package logs
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Event struct {
|
||||||
|
Timestamp string `json:"timestamp"`
|
||||||
|
Category string `json:"category"`
|
||||||
|
EventType string `json:"event_type"`
|
||||||
|
Unit string `json:"unit,omitempty"`
|
||||||
|
Priority string `json:"priority,omitempty"`
|
||||||
|
Hostname string `json:"hostname,omitempty"`
|
||||||
|
Username string `json:"username,omitempty"`
|
||||||
|
Principal string `json:"principal,omitempty"`
|
||||||
|
SourceIP string `json:"source_ip,omitempty"`
|
||||||
|
SessionID string `json:"session_id,omitempty"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Raw string `json:"raw,omitempty"`
|
||||||
|
Fields map[string]string `json:"fields,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEvent(ts time.Time) Event {
|
||||||
|
return Event{Timestamp: ts.UTC().Format(time.RFC3339Nano)}
|
||||||
|
}
|
||||||
7
agent/internal/version/version.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package version
|
||||||
|
|
||||||
|
var (
|
||||||
|
Version = "0.0.1-dev"
|
||||||
|
Commit = ""
|
||||||
|
BuildDate = ""
|
||||||
|
)
|
||||||
BIN
agent/keywarden-agent
Executable file
@@ -1,10 +1,22 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
|
from django.utils.html import format_html
|
||||||
|
try:
|
||||||
|
from unfold.contrib.guardian.admin import GuardedModelAdmin
|
||||||
|
except ImportError: # Fallback for older Unfold builds without guardian admin shim.
|
||||||
|
from guardian.admin import GuardedModelAdmin as GuardianGuardedModelAdmin
|
||||||
|
from unfold.admin import ModelAdmin as UnfoldModelAdmin
|
||||||
|
|
||||||
|
class GuardedModelAdmin(GuardianGuardedModelAdmin, UnfoldModelAdmin):
|
||||||
|
pass
|
||||||
|
|
||||||
from .models import AccessRequest
|
from .models import AccessRequest
|
||||||
|
|
||||||
|
|
||||||
@admin.register(AccessRequest)
|
@admin.register(AccessRequest)
|
||||||
class AccessRequestAdmin(admin.ModelAdmin):
|
class AccessRequestAdmin(GuardedModelAdmin):
|
||||||
|
autocomplete_fields = ("requester", "server", "decided_by")
|
||||||
list_display = (
|
list_display = (
|
||||||
"id",
|
"id",
|
||||||
"requester",
|
"requester",
|
||||||
@@ -13,7 +25,75 @@ class AccessRequestAdmin(admin.ModelAdmin):
|
|||||||
"requested_at",
|
"requested_at",
|
||||||
"expires_at",
|
"expires_at",
|
||||||
"decided_by",
|
"decided_by",
|
||||||
|
"delete_link",
|
||||||
)
|
)
|
||||||
list_filter = ("status", "server")
|
list_filter = ("status", "server")
|
||||||
search_fields = ("requester__username", "requester__email", "server__display_name")
|
search_fields = ("requester__username", "requester__email", "server__display_name")
|
||||||
ordering = ("-requested_at",)
|
ordering = ("-requested_at",)
|
||||||
|
compressed_fields = True
|
||||||
|
actions_on_top = True
|
||||||
|
actions_on_bottom = True
|
||||||
|
def get_readonly_fields(self, request, obj=None):
|
||||||
|
readonly = ["requested_at"]
|
||||||
|
if obj:
|
||||||
|
readonly.extend(["decided_at", "decided_by"])
|
||||||
|
return readonly
|
||||||
|
|
||||||
|
def get_fieldsets(self, request, obj=None):
|
||||||
|
if obj is None:
|
||||||
|
return (
|
||||||
|
(
|
||||||
|
"Request",
|
||||||
|
{
|
||||||
|
"fields": (
|
||||||
|
"requester",
|
||||||
|
"server",
|
||||||
|
"status",
|
||||||
|
"reason",
|
||||||
|
"expires_at",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
(
|
||||||
|
"Request",
|
||||||
|
{
|
||||||
|
"fields": (
|
||||||
|
"requester",
|
||||||
|
"server",
|
||||||
|
"status",
|
||||||
|
"reason",
|
||||||
|
"expires_at",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Decision",
|
||||||
|
{
|
||||||
|
"fields": (
|
||||||
|
"decided_at",
|
||||||
|
"decided_by",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def save_model(self, request, obj, form, change) -> None:
|
||||||
|
if obj.status in {
|
||||||
|
AccessRequest.Status.APPROVED,
|
||||||
|
AccessRequest.Status.DENIED,
|
||||||
|
AccessRequest.Status.REVOKED,
|
||||||
|
AccessRequest.Status.CANCELLED,
|
||||||
|
}:
|
||||||
|
if not obj.decided_at:
|
||||||
|
obj.decided_at = timezone.now()
|
||||||
|
if not obj.decided_by_id and request.user and request.user.is_authenticated:
|
||||||
|
obj.decided_by = request.user
|
||||||
|
super().save_model(request, obj, form, change)
|
||||||
|
|
||||||
|
def delete_link(self, obj: AccessRequest):
|
||||||
|
url = reverse("admin:access_accessrequest_delete", args=[obj.pk])
|
||||||
|
return format_html('<a class="text-red-600" href="{}">Delete</a>', url)
|
||||||
|
|
||||||
|
delete_link.short_description = "Delete"
|
||||||
|
|||||||
@@ -5,3 +5,7 @@ class AccessConfig(AppConfig):
|
|||||||
default_auto_field = "django.db.models.BigAutoField"
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
name = "apps.access"
|
name = "apps.access"
|
||||||
verbose_name = "Access Requests"
|
verbose_name = "Access Requests"
|
||||||
|
|
||||||
|
def ready(self) -> None:
|
||||||
|
from . import signals # noqa: F401
|
||||||
|
return super().ready()
|
||||||
|
|||||||
26
app/apps/access/permissions.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.db.models import Q
|
||||||
|
from django.utils import timezone
|
||||||
|
from guardian.shortcuts import assign_perm, remove_perm
|
||||||
|
|
||||||
|
from .models import AccessRequest
|
||||||
|
|
||||||
|
|
||||||
|
def sync_server_view_perm(access_request: AccessRequest) -> None:
|
||||||
|
if not access_request or not access_request.requester_id or not access_request.server_id:
|
||||||
|
return
|
||||||
|
now = timezone.now()
|
||||||
|
has_valid_access = (
|
||||||
|
AccessRequest.objects.filter(
|
||||||
|
requester_id=access_request.requester_id,
|
||||||
|
server_id=access_request.server_id,
|
||||||
|
status=AccessRequest.Status.APPROVED,
|
||||||
|
)
|
||||||
|
.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
|
||||||
|
.exists()
|
||||||
|
)
|
||||||
|
if has_valid_access:
|
||||||
|
assign_perm("servers.view_server", access_request.requester, access_request.server)
|
||||||
|
return
|
||||||
|
remove_perm("servers.view_server", access_request.requester, access_request.server)
|
||||||
26
app/apps/access/signals.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.db.models.signals import post_save
|
||||||
|
from django.dispatch import receiver
|
||||||
|
from guardian.shortcuts import assign_perm
|
||||||
|
|
||||||
|
from apps.core.rbac import assign_default_object_permissions
|
||||||
|
from .models import AccessRequest
|
||||||
|
from .permissions import sync_server_view_perm
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(post_save, sender=AccessRequest)
|
||||||
|
def assign_access_request_perms(sender, instance: AccessRequest, created: bool, **kwargs) -> None:
|
||||||
|
if not created:
|
||||||
|
sync_server_view_perm(instance)
|
||||||
|
return
|
||||||
|
if instance.requester_id:
|
||||||
|
user = instance.requester
|
||||||
|
for perm in (
|
||||||
|
"access.view_accessrequest",
|
||||||
|
"access.change_accessrequest",
|
||||||
|
"access.delete_accessrequest",
|
||||||
|
):
|
||||||
|
assign_perm(perm, user, instance)
|
||||||
|
assign_default_object_permissions(instance)
|
||||||
|
sync_server_view_perm(instance)
|
||||||
27
app/apps/access/tasks.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from celery import shared_task
|
||||||
|
from django.db import transaction
|
||||||
|
from django.utils import timezone
|
||||||
|
from .models import AccessRequest
|
||||||
|
from .permissions import sync_server_view_perm
|
||||||
|
|
||||||
|
|
||||||
|
@shared_task
|
||||||
|
def expire_access_requests() -> int:
|
||||||
|
now = timezone.now()
|
||||||
|
expired_qs = AccessRequest.objects.select_related("server", "requester").filter(
|
||||||
|
status=AccessRequest.Status.APPROVED,
|
||||||
|
expires_at__isnull=False,
|
||||||
|
expires_at__lte=now,
|
||||||
|
)
|
||||||
|
count = 0
|
||||||
|
for access_request in expired_qs:
|
||||||
|
with transaction.atomic():
|
||||||
|
access_request.status = AccessRequest.Status.EXPIRED
|
||||||
|
access_request.decided_at = now
|
||||||
|
access_request.decided_by = None
|
||||||
|
access_request.save(update_fields=["status", "decided_at", "decided_by"])
|
||||||
|
sync_server_view_perm(access_request)
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
@@ -1,3 +1,58 @@
|
|||||||
|
from django import forms
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
#
|
from django.utils import timezone
|
||||||
# No custom models registered in accounts app. The legacy Account model has been removed.
|
from unfold.admin import ModelAdmin
|
||||||
|
|
||||||
|
from .models import ErasureRequest
|
||||||
|
|
||||||
|
|
||||||
|
class ErasureRequestAdminForm(forms.ModelForm):
|
||||||
|
class Meta:
|
||||||
|
model = ErasureRequest
|
||||||
|
fields = "__all__"
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
cleaned = super().clean()
|
||||||
|
status = cleaned.get("status")
|
||||||
|
decision_reason = (cleaned.get("decision_reason") or "").strip()
|
||||||
|
if status in {ErasureRequest.Status.DENIED, ErasureRequest.Status.PROCESSED} and not decision_reason:
|
||||||
|
raise forms.ValidationError("Decision reason is required for denied or processed requests.")
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(ErasureRequest)
|
||||||
|
class ErasureRequestAdmin(ModelAdmin):
|
||||||
|
form = ErasureRequestAdminForm
|
||||||
|
list_display = ("id", "user", "status", "requested_at", "decided_at", "processed_at")
|
||||||
|
list_filter = ("status", "requested_at", "processed_at")
|
||||||
|
search_fields = ("user__username", "user__email")
|
||||||
|
readonly_fields = ("requested_at", "decided_at", "processed_at", "decided_by", "processed_by")
|
||||||
|
fieldsets = (
|
||||||
|
(
|
||||||
|
"Request",
|
||||||
|
{
|
||||||
|
"fields": ("user", "reason", "status", "requested_at"),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Decision",
|
||||||
|
{
|
||||||
|
"fields": ("decision_reason", "decided_by", "decided_at"),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Processing",
|
||||||
|
{
|
||||||
|
"fields": ("processed_by", "processed_at"),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def save_model(self, request, obj, form, change) -> None:
|
||||||
|
if obj.status == ErasureRequest.Status.PROCESSED:
|
||||||
|
obj.process(request.user, decision_reason=obj.decision_reason)
|
||||||
|
return
|
||||||
|
if obj.status == ErasureRequest.Status.DENIED and not obj.decided_at:
|
||||||
|
obj.decided_at = timezone.now()
|
||||||
|
obj.decided_by = request.user
|
||||||
|
super().save_model(request, obj, form, change)
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from django import forms
|
||||||
|
|
||||||
|
|
||||||
|
class ErasureRequestForm(forms.Form):
|
||||||
|
reason = forms.CharField(
|
||||||
|
label="Reason for erasure request",
|
||||||
|
widget=forms.Textarea(
|
||||||
|
attrs={
|
||||||
|
"rows": 4,
|
||||||
|
"placeholder": "Explain why you are requesting data erasure.",
|
||||||
|
"class": "w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-purple-600 focus:outline-none focus:ring-1 focus:ring-purple-600",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
min_length=10,
|
||||||
|
max_length=2000,
|
||||||
|
)
|
||||||
|
|||||||
75
app/apps/accounts/migrations/0006_erasure_request.py
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
import django.utils.timezone
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("accounts", "0005_unique_user_email_index"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="ErasureRequest",
|
||||||
|
fields=[
|
||||||
|
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||||
|
("reason", models.TextField()),
|
||||||
|
(
|
||||||
|
"status",
|
||||||
|
models.CharField(
|
||||||
|
choices=[("pending", "Pending"), ("denied", "Denied"), ("processed", "Processed")],
|
||||||
|
db_index=True,
|
||||||
|
default="pending",
|
||||||
|
max_length=16,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("requested_at", models.DateTimeField(default=django.utils.timezone.now, editable=False)),
|
||||||
|
("decided_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("decision_reason", models.TextField(blank=True)),
|
||||||
|
("processed_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
(
|
||||||
|
"decided_by",
|
||||||
|
models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.SET_NULL,
|
||||||
|
related_name="erasure_decisions",
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"processed_by",
|
||||||
|
models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.SET_NULL,
|
||||||
|
related_name="erasure_processes",
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"user",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="erasure_requests",
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"verbose_name": "Erasure request",
|
||||||
|
"verbose_name_plural": "Erasure requests",
|
||||||
|
"ordering": ["-requested_at"],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="erasurerequest",
|
||||||
|
index=models.Index(fields=["status", "requested_at"], name="accounts_erasure_status_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="erasurerequest",
|
||||||
|
index=models.Index(fields=["user", "status"], name="accounts_er_user_status_idx"),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1,3 +1,125 @@
|
|||||||
from django.db import models
|
from __future__ import annotations
|
||||||
#
|
|
||||||
# Legacy Account model has been removed. This app now contains URLs/views only.
|
import uuid
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import models, transaction
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
|
|
||||||
|
class ErasureRequest(models.Model):
|
||||||
|
class Status(models.TextChoices):
|
||||||
|
PENDING = "pending", "Pending"
|
||||||
|
DENIED = "denied", "Denied"
|
||||||
|
PROCESSED = "processed", "Processed"
|
||||||
|
|
||||||
|
user = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="erasure_requests",
|
||||||
|
)
|
||||||
|
reason = models.TextField()
|
||||||
|
status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING, db_index=True)
|
||||||
|
requested_at = models.DateTimeField(default=timezone.now, editable=False)
|
||||||
|
decided_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
decided_by = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
on_delete=models.SET_NULL,
|
||||||
|
related_name="erasure_decisions",
|
||||||
|
)
|
||||||
|
decision_reason = models.TextField(blank=True)
|
||||||
|
processed_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
processed_by = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
on_delete=models.SET_NULL,
|
||||||
|
related_name="erasure_processes",
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = "Erasure request"
|
||||||
|
verbose_name_plural = "Erasure requests"
|
||||||
|
ordering = ["-requested_at"]
|
||||||
|
indexes = [
|
||||||
|
models.Index(fields=["status", "requested_at"], name="accounts_erasure_status_idx"),
|
||||||
|
models.Index(fields=["user", "status"], name="accounts_er_user_status_idx"),
|
||||||
|
]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"Erasure request #{self.id} ({self.user_id})"
|
||||||
|
|
||||||
|
def process(self, admin_user, decision_reason: str = "") -> None:
|
||||||
|
if self.status == self.Status.PROCESSED:
|
||||||
|
return
|
||||||
|
now = timezone.now()
|
||||||
|
with transaction.atomic():
|
||||||
|
self._anonymize_user(admin_user, now)
|
||||||
|
self.status = self.Status.PROCESSED
|
||||||
|
self.decided_at = now
|
||||||
|
self.decided_by = admin_user
|
||||||
|
self.decision_reason = (decision_reason or "").strip()
|
||||||
|
self.processed_at = now
|
||||||
|
self.processed_by = admin_user
|
||||||
|
self.save(
|
||||||
|
update_fields=[
|
||||||
|
"status",
|
||||||
|
"decided_at",
|
||||||
|
"decided_by",
|
||||||
|
"decision_reason",
|
||||||
|
"processed_at",
|
||||||
|
"processed_by",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
def _anonymize_user(self, admin_user, now) -> None:
|
||||||
|
from guardian.models import UserObjectPermission
|
||||||
|
|
||||||
|
from apps.access.models import AccessRequest
|
||||||
|
from apps.keys.models import SSHKey
|
||||||
|
|
||||||
|
user = self.user
|
||||||
|
token = uuid.uuid4().hex
|
||||||
|
anonymous_username = f"erased-{token}"
|
||||||
|
anonymous_email = f"{anonymous_username}@erased.local"
|
||||||
|
|
||||||
|
user.username = anonymous_username
|
||||||
|
user.email = anonymous_email
|
||||||
|
user.first_name = ""
|
||||||
|
user.last_name = ""
|
||||||
|
user.is_active = False
|
||||||
|
user.is_staff = False
|
||||||
|
user.is_superuser = False
|
||||||
|
user.last_login = None
|
||||||
|
user.set_unusable_password()
|
||||||
|
user.save(
|
||||||
|
update_fields=[
|
||||||
|
"username",
|
||||||
|
"email",
|
||||||
|
"first_name",
|
||||||
|
"last_name",
|
||||||
|
"is_active",
|
||||||
|
"is_staff",
|
||||||
|
"is_superuser",
|
||||||
|
"last_login",
|
||||||
|
"password",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
user.groups.clear()
|
||||||
|
user.user_permissions.clear()
|
||||||
|
UserObjectPermission.objects.filter(user=user).delete()
|
||||||
|
|
||||||
|
SSHKey.objects.filter(user=user, is_active=True).update(is_active=False, revoked_at=now)
|
||||||
|
AccessRequest.objects.filter(requester=user).update(reason="[redacted]")
|
||||||
|
AccessRequest.objects.filter(
|
||||||
|
requester=user,
|
||||||
|
status__in=[AccessRequest.Status.PENDING, AccessRequest.Status.APPROVED],
|
||||||
|
).update(
|
||||||
|
status=AccessRequest.Status.REVOKED,
|
||||||
|
decided_at=now,
|
||||||
|
decided_by=admin_user,
|
||||||
|
expires_at=now,
|
||||||
|
)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
<h1 class="mb-6 text-xl font-semibold tracking-tight text-gray-900">Sign in</h1>
|
<h1 class="mb-6 text-xl font-semibold tracking-tight text-gray-900">Sign in</h1>
|
||||||
<form method="post" class="space-y-4">
|
<form method="post" class="space-y-4">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<input type="hidden" name="next" value="{% url 'accounts:profile' %}">
|
<input type="hidden" name="next" value="{% url 'servers:dashboard' %}">
|
||||||
<div class="space-y-1.5">
|
<div class="space-y-1.5">
|
||||||
<label class="block text-sm font-medium text-gray-700">Username</label>
|
<label class="block text-sm font-medium text-gray-700">Username</label>
|
||||||
<input type="text" name="username" autocomplete="username" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-purple-600 focus:ring-purple-600">
|
<input type="text" name="username" autocomplete="username" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-purple-600 focus:ring-purple-600">
|
||||||
@@ -35,4 +35,3 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|||||||
@@ -45,5 +45,60 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
<div class="mt-6 rounded-xl border border-gray-200 bg-white p-6 shadow-sm sm:p-8">
|
||||||
|
<h2 class="text-base font-semibold tracking-tight text-gray-900">Data erasure request</h2>
|
||||||
|
<p class="mt-2 text-sm text-gray-600">
|
||||||
|
Submit a GDPR erasure request to anonymize your account data. An administrator
|
||||||
|
must review and approve the request before processing.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% if erasure_request %}
|
||||||
|
<div class="mt-4 rounded-lg border border-gray-200 bg-gray-50 p-4 text-sm text-gray-700">
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span class="font-semibold">Status:</span>
|
||||||
|
<span class="inline-flex items-center rounded-full bg-gray-200 px-2.5 py-1 text-xs font-semibold text-gray-700">
|
||||||
|
{{ erasure_request.status|capfirst }}
|
||||||
|
</span>
|
||||||
|
<span class="text-gray-500">Requested {{ erasure_request.requested_at|date:"M j, Y H:i" }}</span>
|
||||||
|
</div>
|
||||||
|
{% if erasure_request.decided_at %}
|
||||||
|
<p class="mt-2 text-gray-600">
|
||||||
|
Decision {{ erasure_request.decided_at|date:"M j, Y H:i" }}.
|
||||||
|
{% if erasure_request.decision_reason %}
|
||||||
|
Reason: {{ erasure_request.decision_reason }}
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
{% if erasure_request.status == "processed" %}
|
||||||
|
<p class="mt-2 text-gray-600">
|
||||||
|
Your account has been anonymized. Access has been revoked and SSH keys disabled.
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if not erasure_request or erasure_request.status != "pending" %}
|
||||||
|
<form method="post" class="mt-4 space-y-3">
|
||||||
|
{% csrf_token %}
|
||||||
|
<div>
|
||||||
|
<label for="{{ erasure_form.reason.id_for_label }}" class="block text-sm font-medium text-gray-700">
|
||||||
|
Reason for request
|
||||||
|
</label>
|
||||||
|
<div class="mt-1">
|
||||||
|
{{ erasure_form.reason }}
|
||||||
|
</div>
|
||||||
|
{% if erasure_form.reason.errors %}
|
||||||
|
<p class="mt-1 text-sm text-red-600">{{ erasure_form.reason.errors|striptags }}</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if erasure_form.non_field_errors %}
|
||||||
|
<p class="text-sm text-red-600">{{ erasure_form.non_field_errors|striptags }}</p>
|
||||||
|
{% endif %}
|
||||||
|
<button type="submit" class="inline-flex items-center rounded-md bg-purple-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-purple-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-purple-600">
|
||||||
|
Submit erasure request
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,16 +1,37 @@
|
|||||||
from django.contrib.auth.decorators import login_required
|
|
||||||
from django.shortcuts import render
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.shortcuts import redirect
|
|
||||||
from django.contrib.auth import views as auth_views
|
|
||||||
from django.contrib.auth import logout
|
from django.contrib.auth import logout
|
||||||
|
from django.contrib.auth import views as auth_views
|
||||||
|
from django.contrib.auth.decorators import login_required
|
||||||
|
from django.shortcuts import redirect, render
|
||||||
|
|
||||||
|
from .forms import ErasureRequestForm
|
||||||
|
from .models import ErasureRequest
|
||||||
|
|
||||||
|
|
||||||
@login_required(login_url="/accounts/login/")
|
@login_required(login_url="/accounts/login/")
|
||||||
def profile(request):
|
def profile(request):
|
||||||
|
erasure_request = (
|
||||||
|
ErasureRequest.objects.filter(user=request.user).order_by("-requested_at").first()
|
||||||
|
)
|
||||||
|
if request.method == "POST":
|
||||||
|
form = ErasureRequestForm(request.POST)
|
||||||
|
if form.is_valid():
|
||||||
|
if erasure_request and erasure_request.status == ErasureRequest.Status.PENDING:
|
||||||
|
form.add_error(None, "You already have a pending erasure request.")
|
||||||
|
else:
|
||||||
|
ErasureRequest.objects.create(
|
||||||
|
user=request.user,
|
||||||
|
reason=form.cleaned_data["reason"].strip(),
|
||||||
|
)
|
||||||
|
return redirect("accounts:profile")
|
||||||
|
else:
|
||||||
|
form = ErasureRequestForm()
|
||||||
|
|
||||||
context = {
|
context = {
|
||||||
"user": request.user,
|
"user": request.user,
|
||||||
"auth_mode": getattr(settings, "KEYWARDEN_AUTH_MODE", "hybrid"),
|
"auth_mode": getattr(settings, "KEYWARDEN_AUTH_MODE", "hybrid"),
|
||||||
|
"erasure_request": erasure_request,
|
||||||
|
"erasure_form": form,
|
||||||
}
|
}
|
||||||
return render(request, "accounts/profile.html", context)
|
return render(request, "accounts/profile.html", context)
|
||||||
|
|
||||||
@@ -26,4 +47,3 @@ def login_view(request):
|
|||||||
def logout_view(request):
|
def logout_view(request):
|
||||||
logout(request)
|
logout(request)
|
||||||
return redirect(getattr(settings, "LOGOUT_REDIRECT_URL", "/"))
|
return redirect(getattr(settings, "LOGOUT_REDIRECT_URL", "/"))
|
||||||
|
|
||||||
|
|||||||
124
app/apps/audit/middleware.py
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import time
|
||||||
|
|
||||||
|
from django.utils import timezone
|
||||||
|
from django.utils.text import slugify
|
||||||
|
|
||||||
|
from .models import AuditEventType, AuditLog
|
||||||
|
from .utils import get_client_ip, get_request_id
|
||||||
|
|
||||||
|
_EVENT_CACHE: dict[str, AuditEventType] = {}
|
||||||
|
_SKIP_PREFIXES = ("/api/v1/audit", "/api/v1/user")
|
||||||
|
_SKIP_SUFFIXES = ("/health", "/health/")
|
||||||
|
|
||||||
|
def _is_api_request(path: str) -> bool:
|
||||||
|
return path == "/api" or path.startswith("/api/")
|
||||||
|
|
||||||
|
|
||||||
|
def _should_log_request(path: str) -> bool:
|
||||||
|
if not _is_api_request(path):
|
||||||
|
return False
|
||||||
|
if path in _SKIP_PREFIXES:
|
||||||
|
return False
|
||||||
|
if any(path.startswith(prefix + "/") for prefix in _SKIP_PREFIXES):
|
||||||
|
return False
|
||||||
|
if any(path.endswith(suffix) for suffix in _SKIP_SUFFIXES):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_route(request, fallback: str) -> str:
|
||||||
|
match = getattr(request, "resolver_match", None)
|
||||||
|
route = getattr(match, "route", None) if match else None
|
||||||
|
if route:
|
||||||
|
return route if route.startswith("/") else f"/{route}"
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
|
||||||
|
def _event_key_for(method: str, route: str) -> str:
|
||||||
|
base = f"api_{method.lower()}_{route}"
|
||||||
|
slug = slugify(base)
|
||||||
|
if not slug:
|
||||||
|
return "api_request"
|
||||||
|
if len(slug) <= 64:
|
||||||
|
return slug
|
||||||
|
digest = hashlib.sha1(slug.encode("utf-8")).hexdigest()[:8]
|
||||||
|
prefix_len = 64 - len(digest) - 1
|
||||||
|
return f"{slug[:prefix_len]}-{digest}"
|
||||||
|
|
||||||
|
|
||||||
|
def _event_title_for(method: str, route: str) -> str:
|
||||||
|
title = f"API {method.upper()} {route}"
|
||||||
|
if len(title) <= 128:
|
||||||
|
return title
|
||||||
|
return f"{title[:125]}..."
|
||||||
|
|
||||||
|
|
||||||
|
def _get_endpoint_event(method: str, route: str) -> AuditEventType:
|
||||||
|
key = _event_key_for(method, route)
|
||||||
|
cached = _EVENT_CACHE.get(key)
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
|
event, _ = AuditEventType.objects.get_or_create(
|
||||||
|
key=key,
|
||||||
|
defaults={
|
||||||
|
"title": _event_title_for(method, route),
|
||||||
|
"default_severity": AuditEventType.Severity.INFO,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
_EVENT_CACHE[key] = event
|
||||||
|
return event
|
||||||
|
|
||||||
|
|
||||||
|
class ApiAuditLogMiddleware:
|
||||||
|
def __init__(self, get_response):
|
||||||
|
self.get_response = get_response
|
||||||
|
|
||||||
|
def __call__(self, request):
|
||||||
|
path = request.path_info or request.path
|
||||||
|
if not _should_log_request(path):
|
||||||
|
return self.get_response(request)
|
||||||
|
|
||||||
|
start = time.monotonic()
|
||||||
|
try:
|
||||||
|
response = self.get_response(request)
|
||||||
|
except Exception as exc:
|
||||||
|
duration_ms = int((time.monotonic() - start) * 1000)
|
||||||
|
self._write_log(request, path, 500, duration_ms, error=type(exc).__name__)
|
||||||
|
raise
|
||||||
|
|
||||||
|
duration_ms = int((time.monotonic() - start) * 1000)
|
||||||
|
self._write_log(request, path, response.status_code, duration_ms)
|
||||||
|
return response
|
||||||
|
|
||||||
|
def _write_log(self, request, path: str, status_code: int, duration_ms: int, error: str | None = None) -> None:
|
||||||
|
try:
|
||||||
|
route = _resolve_route(request, path)
|
||||||
|
user = getattr(request, "user", None)
|
||||||
|
actor = user if getattr(user, "is_authenticated", False) else None
|
||||||
|
metadata = {
|
||||||
|
"method": request.method,
|
||||||
|
"path": path,
|
||||||
|
"route": route,
|
||||||
|
"status_code": status_code,
|
||||||
|
"duration_ms": duration_ms,
|
||||||
|
"query_string": request.META.get("QUERY_STRING", ""),
|
||||||
|
}
|
||||||
|
if error:
|
||||||
|
metadata["error"] = error
|
||||||
|
AuditLog.objects.create(
|
||||||
|
created_at=timezone.now(),
|
||||||
|
actor=actor,
|
||||||
|
event_type=_get_endpoint_event(request.method, route),
|
||||||
|
message=f"API request {request.method} {route} -> {status_code}",
|
||||||
|
severity=AuditEventType.Severity.INFO,
|
||||||
|
source=AuditLog.Source.API,
|
||||||
|
ip_address=get_client_ip(request),
|
||||||
|
user_agent=request.META.get("HTTP_USER_AGENT", ""),
|
||||||
|
request_id=get_request_id(request),
|
||||||
|
metadata=metadata,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
@@ -6,6 +6,7 @@ from django.dispatch import receiver
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
|
||||||
from .models import AuditEventType, AuditLog
|
from .models import AuditEventType, AuditLog
|
||||||
|
from .utils import get_client_ip
|
||||||
|
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
|
|
||||||
@@ -28,7 +29,7 @@ def on_user_logged_in(sender, request, user: User, **kwargs):
|
|||||||
message=f"User {user} logged in",
|
message=f"User {user} logged in",
|
||||||
severity=event.default_severity,
|
severity=event.default_severity,
|
||||||
source=AuditLog.Source.UI,
|
source=AuditLog.Source.UI,
|
||||||
ip_address=(request.META.get("REMOTE_ADDR") if request else None),
|
ip_address=get_client_ip(request),
|
||||||
user_agent=(request.META.get("HTTP_USER_AGENT") if request else ""),
|
user_agent=(request.META.get("HTTP_USER_AGENT") if request else ""),
|
||||||
metadata={"path": request.path} if request else {},
|
metadata={"path": request.path} if request else {},
|
||||||
)
|
)
|
||||||
@@ -44,9 +45,7 @@ def on_user_logged_out(sender, request, user: User, **kwargs):
|
|||||||
message=f"User {user} logged out",
|
message=f"User {user} logged out",
|
||||||
severity=event.default_severity,
|
severity=event.default_severity,
|
||||||
source=AuditLog.Source.UI,
|
source=AuditLog.Source.UI,
|
||||||
ip_address=(request.META.get("REMOTE_ADDR") if request else None),
|
ip_address=get_client_ip(request),
|
||||||
user_agent=(request.META.get("HTTP_USER_AGENT") if request else ""),
|
user_agent=(request.META.get("HTTP_USER_AGENT") if request else ""),
|
||||||
metadata={"path": request.path} if request else {},
|
metadata={"path": request.path} if request else {},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
44
app/apps/audit/utils.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_ip(value: str | None) -> str | None:
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
candidate = value.strip()
|
||||||
|
if not candidate:
|
||||||
|
return None
|
||||||
|
if candidate.startswith("[") and "]" in candidate:
|
||||||
|
candidate = candidate[1 : candidate.index("]")]
|
||||||
|
elif candidate.count(":") == 1 and candidate.rsplit(":", 1)[1].isdigit():
|
||||||
|
candidate = candidate.rsplit(":", 1)[0]
|
||||||
|
try:
|
||||||
|
return str(ipaddress.ip_address(candidate))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_client_ip(request) -> str | None:
|
||||||
|
if not request:
|
||||||
|
return None
|
||||||
|
x_real_ip = _normalize_ip(request.META.get("HTTP_X_REAL_IP"))
|
||||||
|
if x_real_ip:
|
||||||
|
return x_real_ip
|
||||||
|
forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR", "")
|
||||||
|
if forwarded_for:
|
||||||
|
for part in forwarded_for.split(","):
|
||||||
|
ip = _normalize_ip(part)
|
||||||
|
if ip:
|
||||||
|
return ip
|
||||||
|
return _normalize_ip(request.META.get("REMOTE_ADDR"))
|
||||||
|
|
||||||
|
|
||||||
|
def get_request_id(request) -> str:
|
||||||
|
if not request:
|
||||||
|
return ""
|
||||||
|
return (
|
||||||
|
request.META.get("HTTP_X_REQUEST_ID")
|
||||||
|
or request.META.get("HTTP_X_CORRELATION_ID")
|
||||||
|
or ""
|
||||||
|
)
|
||||||
21
app/apps/core/apps.py
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.apps import AppConfig
|
||||||
|
from django.db.models.signals import post_migrate
|
||||||
|
|
||||||
|
|
||||||
|
class CoreConfig(AppConfig):
|
||||||
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
|
name = "apps.core"
|
||||||
|
label = "core"
|
||||||
|
verbose_name = "Core"
|
||||||
|
|
||||||
|
def ready(self) -> None:
|
||||||
|
from .rbac import assign_role_permissions, ensure_role_groups
|
||||||
|
|
||||||
|
def _ensure_roles(**_kwargs) -> None:
|
||||||
|
ensure_role_groups()
|
||||||
|
assign_role_permissions()
|
||||||
|
|
||||||
|
post_migrate.connect(_ensure_roles, dispatch_uid="core_rbac")
|
||||||
|
return super().ready()
|
||||||
@@ -3,6 +3,8 @@ import os
|
|||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from django.core.management.base import BaseCommand
|
from django.core.management.base import BaseCommand
|
||||||
|
|
||||||
|
from apps.core.rbac import ROLE_ADMIN, set_user_role
|
||||||
|
|
||||||
|
|
||||||
class Command(BaseCommand):
|
class Command(BaseCommand):
|
||||||
help = "Ensure a Django superuser exists using environment variables"
|
help = "Ensure a Django superuser exists using environment variables"
|
||||||
@@ -41,6 +43,7 @@ class Command(BaseCommand):
|
|||||||
|
|
||||||
if created:
|
if created:
|
||||||
user.set_password(password)
|
user.set_password(password)
|
||||||
|
set_user_role(user, ROLE_ADMIN)
|
||||||
user.save()
|
user.save()
|
||||||
self.stdout.write(self.style.SUCCESS(f"Superuser '{username}' created."))
|
self.stdout.write(self.style.SUCCESS(f"Superuser '{username}' created."))
|
||||||
return
|
return
|
||||||
@@ -59,10 +62,11 @@ class Command(BaseCommand):
|
|||||||
user.is_superuser = True
|
user.is_superuser = True
|
||||||
changed = True
|
changed = True
|
||||||
|
|
||||||
|
set_user_role(user, ROLE_ADMIN)
|
||||||
|
|
||||||
if changed:
|
if changed:
|
||||||
user.save()
|
user.save()
|
||||||
self.stdout.write(self.style.SUCCESS(f"Superuser '{username}' updated."))
|
self.stdout.write(self.style.SUCCESS(f"Superuser '{username}' updated."))
|
||||||
else:
|
else:
|
||||||
self.stdout.write(self.style.SUCCESS(f"Superuser '{username}' already present."))
|
self.stdout.write(self.style.SUCCESS(f"Superuser '{username}' already present."))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
51
app/apps/core/management/commands/sync_object_perms.py
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
|
||||||
|
from guardian.shortcuts import assign_perm
|
||||||
|
|
||||||
|
from apps.access.models import AccessRequest
|
||||||
|
from apps.core.rbac import assign_default_object_permissions
|
||||||
|
from apps.keys.models import SSHKey
|
||||||
|
from apps.servers.models import Server
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = "Backfill guardian object permissions for access requests and SSH keys."
|
||||||
|
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
access_count = 0
|
||||||
|
for access_request in AccessRequest.objects.select_related("requester"):
|
||||||
|
if not access_request.requester_id:
|
||||||
|
assign_default_object_permissions(access_request)
|
||||||
|
else:
|
||||||
|
for perm in (
|
||||||
|
"access.view_accessrequest",
|
||||||
|
"access.change_accessrequest",
|
||||||
|
"access.delete_accessrequest",
|
||||||
|
):
|
||||||
|
assign_perm(perm, access_request.requester, access_request)
|
||||||
|
assign_default_object_permissions(access_request)
|
||||||
|
access_count += 1
|
||||||
|
|
||||||
|
key_count = 0
|
||||||
|
for key in SSHKey.objects.select_related("user"):
|
||||||
|
if not key.user_id:
|
||||||
|
assign_default_object_permissions(key)
|
||||||
|
else:
|
||||||
|
for perm in ("keys.view_sshkey", "keys.change_sshkey", "keys.delete_sshkey"):
|
||||||
|
assign_perm(perm, key.user, key)
|
||||||
|
assign_default_object_permissions(key)
|
||||||
|
key_count += 1
|
||||||
|
|
||||||
|
server_count = 0
|
||||||
|
for server in Server.objects.all():
|
||||||
|
assign_default_object_permissions(server)
|
||||||
|
server_count += 1
|
||||||
|
|
||||||
|
self.stdout.write(
|
||||||
|
self.style.SUCCESS(
|
||||||
|
"Synced object permissions for "
|
||||||
|
f"{access_count} access requests, "
|
||||||
|
f"{key_count} SSH keys, "
|
||||||
|
f"and {server_count} servers."
|
||||||
|
)
|
||||||
|
)
|
||||||
155
app/apps/core/rbac.py
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.contrib.auth.models import Group, Permission
|
||||||
|
from guardian.shortcuts import assign_perm
|
||||||
|
from ninja.errors import HttpError
|
||||||
|
|
||||||
|
ROLE_ADMIN = "administrator"
|
||||||
|
ROLE_OPERATOR = "operator"
|
||||||
|
ROLE_AUDITOR = "auditor"
|
||||||
|
ROLE_USER = "user"
|
||||||
|
|
||||||
|
ROLE_ORDER = (ROLE_ADMIN, ROLE_OPERATOR, ROLE_AUDITOR, ROLE_USER)
|
||||||
|
ROLE_ALL = ROLE_ORDER
|
||||||
|
ROLE_ALIASES = {"admin": ROLE_ADMIN}
|
||||||
|
ROLE_INPUTS = tuple(sorted(set(ROLE_ORDER) | set(ROLE_ALIASES.keys())))
|
||||||
|
|
||||||
|
def _model_perms(app_label: str, model: str, actions: list[str]) -> list[str]:
|
||||||
|
return [f"{app_label}.{action}_{model}" for action in actions]
|
||||||
|
|
||||||
|
|
||||||
|
ROLE_PERMISSIONS = {
|
||||||
|
ROLE_ADMIN: [],
|
||||||
|
ROLE_OPERATOR: [
|
||||||
|
*_model_perms("servers", "server", ["view"]),
|
||||||
|
*_model_perms("access", "accessrequest", ["add", "view", "change", "delete"]),
|
||||||
|
*_model_perms("keys", "sshkey", ["add", "view", "change", "delete"]),
|
||||||
|
*_model_perms("telemetry", "telemetryevent", ["add", "view"]),
|
||||||
|
*_model_perms("audit", "auditlog", ["view"]),
|
||||||
|
*_model_perms("audit", "auditeventtype", ["view"]),
|
||||||
|
*_model_perms("auth", "user", ["add", "view"]),
|
||||||
|
],
|
||||||
|
ROLE_AUDITOR: [
|
||||||
|
*_model_perms("audit", "auditlog", ["view"]),
|
||||||
|
*_model_perms("audit", "auditeventtype", ["view"]),
|
||||||
|
],
|
||||||
|
ROLE_USER: [
|
||||||
|
*_model_perms("servers", "server", ["view"]),
|
||||||
|
*_model_perms("access", "accessrequest", ["add"]),
|
||||||
|
*_model_perms("keys", "sshkey", ["add"]),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
OBJECT_PERMISSION_MODELS = {
|
||||||
|
("servers", "server"),
|
||||||
|
("access", "accessrequest"),
|
||||||
|
("keys", "sshkey"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_role(role: str) -> str:
|
||||||
|
normalized = (role or "").strip().lower()
|
||||||
|
return ROLE_ALIASES.get(normalized, normalized)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_role_groups() -> None:
|
||||||
|
for role in ROLE_ORDER:
|
||||||
|
Group.objects.get_or_create(name=role)
|
||||||
|
|
||||||
|
|
||||||
|
def assign_role_permissions() -> None:
|
||||||
|
ensure_role_groups()
|
||||||
|
for role, perm_codes in ROLE_PERMISSIONS.items():
|
||||||
|
group = Group.objects.get(name=role)
|
||||||
|
if role == ROLE_ADMIN:
|
||||||
|
group.permissions.set(Permission.objects.all())
|
||||||
|
continue
|
||||||
|
perms = []
|
||||||
|
for code in perm_codes:
|
||||||
|
if "." not in code:
|
||||||
|
continue
|
||||||
|
app_label, codename = code.split(".", 1)
|
||||||
|
try:
|
||||||
|
perms.append(
|
||||||
|
Permission.objects.get(
|
||||||
|
content_type__app_label=app_label,
|
||||||
|
codename=codename,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Permission.DoesNotExist:
|
||||||
|
continue
|
||||||
|
group.permissions.set(perms)
|
||||||
|
|
||||||
|
|
||||||
|
def assign_default_object_permissions(instance) -> None:
|
||||||
|
app_label = instance._meta.app_label
|
||||||
|
model_name = instance._meta.model_name
|
||||||
|
if (app_label, model_name) not in OBJECT_PERMISSION_MODELS:
|
||||||
|
return
|
||||||
|
ensure_role_groups()
|
||||||
|
groups = {group.name: group for group in Group.objects.filter(name__in=ROLE_ORDER)}
|
||||||
|
for role, perm_codes in ROLE_PERMISSIONS.items():
|
||||||
|
if role == ROLE_ADMIN:
|
||||||
|
continue
|
||||||
|
group = groups.get(role)
|
||||||
|
if not group:
|
||||||
|
continue
|
||||||
|
for code in perm_codes:
|
||||||
|
if "." not in code:
|
||||||
|
continue
|
||||||
|
perm_app, codename = code.split(".", 1)
|
||||||
|
if perm_app != app_label:
|
||||||
|
continue
|
||||||
|
if not codename.endswith(f"_{model_name}"):
|
||||||
|
continue
|
||||||
|
if codename.startswith("add_"):
|
||||||
|
continue
|
||||||
|
assign_perm(code, group, instance)
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_role(user, default: str = ROLE_USER) -> str | None:
|
||||||
|
if not user or not getattr(user, "is_authenticated", False):
|
||||||
|
return None
|
||||||
|
if getattr(user, "is_superuser", False):
|
||||||
|
return ROLE_ADMIN
|
||||||
|
group_names = set(user.groups.values_list("name", flat=True))
|
||||||
|
for role in ROLE_ORDER:
|
||||||
|
if role in group_names:
|
||||||
|
return role
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def set_user_role(user, role: str) -> str:
|
||||||
|
canonical = normalize_role(role)
|
||||||
|
if canonical not in ROLE_ORDER:
|
||||||
|
raise ValueError(f"Invalid role: {role}")
|
||||||
|
ensure_role_groups()
|
||||||
|
role_groups = list(Group.objects.filter(name__in=ROLE_ORDER))
|
||||||
|
if role_groups:
|
||||||
|
user.groups.remove(*role_groups)
|
||||||
|
target_group = Group.objects.get(name=canonical)
|
||||||
|
user.groups.add(target_group)
|
||||||
|
if canonical == ROLE_ADMIN:
|
||||||
|
user.is_staff = True
|
||||||
|
user.is_superuser = True
|
||||||
|
elif canonical in {ROLE_OPERATOR, ROLE_AUDITOR}:
|
||||||
|
user.is_staff = True
|
||||||
|
user.is_superuser = False
|
||||||
|
else:
|
||||||
|
user.is_staff = False
|
||||||
|
user.is_superuser = False
|
||||||
|
return canonical
|
||||||
|
|
||||||
|
|
||||||
|
def require_authenticated(request) -> None:
|
||||||
|
user = getattr(request, "user", None)
|
||||||
|
if not user or not getattr(user, "is_authenticated", False):
|
||||||
|
raise HttpError(403, "Forbidden")
|
||||||
|
|
||||||
|
|
||||||
|
def require_perms(request, *perms: str) -> None:
|
||||||
|
user = getattr(request, "user", None)
|
||||||
|
if not user or not getattr(user, "is_authenticated", False):
|
||||||
|
raise HttpError(403, "Forbidden")
|
||||||
|
if not user.has_perms(perms):
|
||||||
|
raise HttpError(403, "Forbidden")
|
||||||
@@ -1,10 +1,18 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
try:
|
||||||
|
from unfold.contrib.guardian.admin import GuardedModelAdmin
|
||||||
|
except ImportError: # Fallback for older Unfold builds without guardian admin shim.
|
||||||
|
from guardian.admin import GuardedModelAdmin as GuardianGuardedModelAdmin
|
||||||
|
from unfold.admin import ModelAdmin as UnfoldModelAdmin
|
||||||
|
|
||||||
|
class GuardedModelAdmin(GuardianGuardedModelAdmin, UnfoldModelAdmin):
|
||||||
|
pass
|
||||||
|
|
||||||
from .models import SSHKey
|
from .models import SSHKey
|
||||||
|
|
||||||
|
|
||||||
@admin.register(SSHKey)
|
@admin.register(SSHKey)
|
||||||
class SSHKeyAdmin(admin.ModelAdmin):
|
class SSHKeyAdmin(GuardedModelAdmin):
|
||||||
list_display = ("id", "user", "name", "key_type", "fingerprint", "is_active", "created_at")
|
list_display = ("id", "user", "name", "key_type", "fingerprint", "is_active", "created_at")
|
||||||
list_filter = ("is_active", "key_type")
|
list_filter = ("is_active", "key_type")
|
||||||
search_fields = ("name", "user__username", "user__email", "fingerprint")
|
search_fields = ("name", "user__username", "user__email", "fingerprint")
|
||||||
|
|||||||
@@ -5,3 +5,7 @@ class KeysConfig(AppConfig):
|
|||||||
default_auto_field = "django.db.models.BigAutoField"
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
name = "apps.keys"
|
name = "apps.keys"
|
||||||
verbose_name = "SSH Keys"
|
verbose_name = "SSH Keys"
|
||||||
|
|
||||||
|
def ready(self) -> None:
|
||||||
|
from . import signals # noqa: F401
|
||||||
|
return super().ready()
|
||||||
|
|||||||
19
app/apps/keys/signals.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.db.models.signals import post_save
|
||||||
|
from django.dispatch import receiver
|
||||||
|
from guardian.shortcuts import assign_perm
|
||||||
|
|
||||||
|
from apps.core.rbac import assign_default_object_permissions
|
||||||
|
from .models import SSHKey
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(post_save, sender=SSHKey)
|
||||||
|
def assign_ssh_key_perms(sender, instance: SSHKey, created: bool, **kwargs) -> None:
|
||||||
|
if not created:
|
||||||
|
return
|
||||||
|
if instance.user_id:
|
||||||
|
user = instance.user
|
||||||
|
for perm in ("keys.view_sshkey", "keys.change_sshkey", "keys.delete_sshkey"):
|
||||||
|
assign_perm(perm, user, instance)
|
||||||
|
assign_default_object_permissions(instance)
|
||||||
@@ -1,16 +1,34 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.utils.html import format_html
|
from django.utils.html import format_html
|
||||||
from .models import Server
|
try:
|
||||||
|
from unfold.contrib.guardian.admin import GuardedModelAdmin
|
||||||
|
except ImportError: # Fallback for older Unfold builds without guardian admin shim.
|
||||||
|
from guardian.admin import GuardedModelAdmin as GuardianGuardedModelAdmin
|
||||||
|
from unfold.admin import ModelAdmin as UnfoldModelAdmin
|
||||||
|
|
||||||
|
class GuardedModelAdmin(GuardianGuardedModelAdmin, UnfoldModelAdmin):
|
||||||
|
pass
|
||||||
|
|
||||||
|
from .models import AgentCertificateAuthority, EnrollmentToken, Server
|
||||||
|
|
||||||
|
|
||||||
@admin.register(Server)
|
@admin.register(Server)
|
||||||
class ServerAdmin(admin.ModelAdmin):
|
class ServerAdmin(GuardedModelAdmin):
|
||||||
list_display = ("avatar", "display_name", "hostname", "ipv4", "ipv6", "created_at")
|
list_display = ("avatar", "display_name", "hostname", "ipv4", "ipv6", "agent_enrolled_at", "created_at")
|
||||||
list_display_links = ("display_name",)
|
list_display_links = ("display_name",)
|
||||||
search_fields = ("display_name", "hostname", "ipv4", "ipv6")
|
search_fields = ("display_name", "hostname", "ipv4", "ipv6")
|
||||||
list_filter = ("created_at",)
|
list_filter = ("created_at",)
|
||||||
readonly_fields = ("created_at", "updated_at")
|
readonly_fields = ("created_at", "updated_at", "agent_enrolled_at")
|
||||||
fields = ("display_name", "hostname", "ipv4", "ipv6", "image", "created_at", "updated_at")
|
fields = (
|
||||||
|
"display_name",
|
||||||
|
"hostname",
|
||||||
|
"ipv4",
|
||||||
|
"ipv6",
|
||||||
|
"image",
|
||||||
|
"agent_enrolled_at",
|
||||||
|
"created_at",
|
||||||
|
"updated_at",
|
||||||
|
)
|
||||||
|
|
||||||
def avatar(self, obj: Server):
|
def avatar(self, obj: Server):
|
||||||
if obj.image_url:
|
if obj.image_url:
|
||||||
@@ -27,3 +45,50 @@ class ServerAdmin(admin.ModelAdmin):
|
|||||||
avatar.short_description = ""
|
avatar.short_description = ""
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(EnrollmentToken)
|
||||||
|
class EnrollmentTokenAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ("token", "created_at", "expires_at", "used_at", "server")
|
||||||
|
list_filter = ("created_at", "used_at")
|
||||||
|
search_fields = ("token", "server__display_name", "server__hostname")
|
||||||
|
readonly_fields = ("token", "created_at", "used_at", "server", "created_by")
|
||||||
|
fields = ("token", "expires_at", "created_by", "created_at", "used_at", "server")
|
||||||
|
|
||||||
|
def save_model(self, request, obj, form, change) -> None:
|
||||||
|
if not obj.pk:
|
||||||
|
obj.ensure_token()
|
||||||
|
if request.user and request.user.is_authenticated and not obj.created_by_id:
|
||||||
|
obj.created_by = request.user
|
||||||
|
super().save_model(request, obj, form, change)
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(AgentCertificateAuthority)
|
||||||
|
class AgentCertificateAuthorityAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ("name", "is_active", "created_at", "revoked_at")
|
||||||
|
list_filter = ("is_active", "created_at", "revoked_at")
|
||||||
|
search_fields = ("name", "fingerprint")
|
||||||
|
readonly_fields = ("cert_pem", "fingerprint", "serial", "created_at", "revoked_at", "created_by")
|
||||||
|
fields = (
|
||||||
|
"name",
|
||||||
|
"is_active",
|
||||||
|
"cert_pem",
|
||||||
|
"fingerprint",
|
||||||
|
"serial",
|
||||||
|
"created_by",
|
||||||
|
"created_at",
|
||||||
|
"revoked_at",
|
||||||
|
)
|
||||||
|
actions = ["revoke_selected"]
|
||||||
|
|
||||||
|
def save_model(self, request, obj, form, change) -> None:
|
||||||
|
if request.user and request.user.is_authenticated and not obj.created_by_id:
|
||||||
|
obj.created_by = request.user
|
||||||
|
obj.ensure_material()
|
||||||
|
if obj.is_active:
|
||||||
|
AgentCertificateAuthority.objects.exclude(pk=obj.pk).update(is_active=False)
|
||||||
|
super().save_model(request, obj, form, change)
|
||||||
|
|
||||||
|
@admin.action(description="Revoke selected CAs")
|
||||||
|
def revoke_selected(self, request, queryset):
|
||||||
|
for ca in queryset:
|
||||||
|
ca.revoke()
|
||||||
|
ca.save(update_fields=["is_active", "revoked_at"])
|
||||||
|
|||||||
@@ -6,4 +6,7 @@ class ServersConfig(AppConfig):
|
|||||||
name = "apps.servers"
|
name = "apps.servers"
|
||||||
verbose_name = "Servers"
|
verbose_name = "Servers"
|
||||||
|
|
||||||
|
def ready(self) -> None:
|
||||||
|
from . import signals # noqa: F401
|
||||||
|
return super().ready()
|
||||||
|
|
||||||
|
|||||||
73
app/apps/servers/migrations/0002_agent_enrollment.py
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.utils.timezone
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("servers", "0001_initial"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="server",
|
||||||
|
name="agent_cert_fingerprint",
|
||||||
|
field=models.CharField(blank=True, max_length=128, null=True),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="server",
|
||||||
|
name="agent_cert_serial",
|
||||||
|
field=models.CharField(blank=True, max_length=64, null=True),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="server",
|
||||||
|
name="agent_enrolled_at",
|
||||||
|
field=models.DateTimeField(blank=True, null=True),
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="EnrollmentToken",
|
||||||
|
fields=[
|
||||||
|
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||||
|
("token", models.CharField(max_length=128, unique=True)),
|
||||||
|
("created_at", models.DateTimeField(default=django.utils.timezone.now, editable=False)),
|
||||||
|
("expires_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("used_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
(
|
||||||
|
"created_by",
|
||||||
|
models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.SET_NULL,
|
||||||
|
related_name="server_enrollment_tokens",
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"server",
|
||||||
|
models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.SET_NULL,
|
||||||
|
related_name="enrollment_tokens",
|
||||||
|
to="servers.server",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"verbose_name": "Enrollment token",
|
||||||
|
"verbose_name_plural": "Enrollment tokens",
|
||||||
|
"ordering": ["-created_at"],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="enrollmenttoken",
|
||||||
|
index=models.Index(fields=["created_at"], name="servers_enroll_created_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="enrollmenttoken",
|
||||||
|
index=models.Index(fields=["used_at"], name="servers_enroll_used_idx"),
|
||||||
|
),
|
||||||
|
]
|
||||||
44
app/apps/servers/migrations/0003_agent_ca.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
import django.utils.timezone
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("servers", "0002_agent_enrollment"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="AgentCertificateAuthority",
|
||||||
|
fields=[
|
||||||
|
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||||
|
("name", models.CharField(default="Keywarden Agent CA", max_length=128)),
|
||||||
|
("cert_pem", models.TextField()),
|
||||||
|
("key_pem", models.TextField()),
|
||||||
|
("fingerprint", models.CharField(blank=True, max_length=128)),
|
||||||
|
("serial", models.CharField(blank=True, max_length=64)),
|
||||||
|
("created_at", models.DateTimeField(default=django.utils.timezone.now, editable=False)),
|
||||||
|
("revoked_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("is_active", models.BooleanField(db_index=True, default=True)),
|
||||||
|
(
|
||||||
|
"created_by",
|
||||||
|
models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.SET_NULL,
|
||||||
|
related_name="agent_certificate_authorities",
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"verbose_name": "Agent certificate authority",
|
||||||
|
"verbose_name_plural": "Agent certificate authorities",
|
||||||
|
"ordering": ["-created_at"],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
59
app/apps/servers/migrations/0004_server_account.py
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
import django.utils.timezone
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("servers", "0003_agent_ca"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="ServerAccount",
|
||||||
|
fields=[
|
||||||
|
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||||
|
("system_username", models.CharField(max_length=128)),
|
||||||
|
("is_present", models.BooleanField(db_index=True, default=False)),
|
||||||
|
("last_synced_at", models.DateTimeField(default=django.utils.timezone.now, editable=False)),
|
||||||
|
("created_at", models.DateTimeField(default=django.utils.timezone.now, editable=False)),
|
||||||
|
("updated_at", models.DateTimeField(auto_now=True)),
|
||||||
|
(
|
||||||
|
"server",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="accounts",
|
||||||
|
to="servers.server",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"user",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="server_accounts",
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"verbose_name": "Server account",
|
||||||
|
"verbose_name_plural": "Server accounts",
|
||||||
|
"ordering": ["server_id", "user_id"],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.AddConstraint(
|
||||||
|
model_name="serveraccount",
|
||||||
|
constraint=models.UniqueConstraint(fields=("server", "user"), name="unique_server_account"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="serveraccount",
|
||||||
|
index=models.Index(fields=["server", "user"], name="servers_account_user_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="serveraccount",
|
||||||
|
index=models.Index(fields=["server", "is_present"], name="servers_account_present_idx"),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1,8 +1,16 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from cryptography import x509
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||||
|
from cryptography.x509.oid import NameOID
|
||||||
|
from django.conf import settings
|
||||||
from django.core.validators import RegexValidator
|
from django.core.validators import RegexValidator
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.text import slugify
|
from django.utils import timezone
|
||||||
|
|
||||||
|
|
||||||
hostname_validator = RegexValidator(
|
hostname_validator = RegexValidator(
|
||||||
@@ -17,6 +25,9 @@ class Server(models.Model):
|
|||||||
ipv4 = models.GenericIPAddressField(null=True, blank=True, protocol="IPv4", unique=True)
|
ipv4 = models.GenericIPAddressField(null=True, blank=True, protocol="IPv4", unique=True)
|
||||||
ipv6 = models.GenericIPAddressField(null=True, blank=True, protocol="IPv6", unique=True)
|
ipv6 = models.GenericIPAddressField(null=True, blank=True, protocol="IPv6", unique=True)
|
||||||
image = models.ImageField(upload_to="servers/", null=True, blank=True)
|
image = models.ImageField(upload_to="servers/", null=True, blank=True)
|
||||||
|
agent_enrolled_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
agent_cert_fingerprint = models.CharField(max_length=128, null=True, blank=True)
|
||||||
|
agent_cert_serial = models.CharField(max_length=64, null=True, blank=True)
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
updated_at = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
@@ -41,3 +52,135 @@ class Server(models.Model):
|
|||||||
return (self.display_name or "?").strip()[:1].upper() or "?"
|
return (self.display_name or "?").strip()[:1].upper() or "?"
|
||||||
|
|
||||||
|
|
||||||
|
class EnrollmentToken(models.Model):
|
||||||
|
token = models.CharField(max_length=128, unique=True)
|
||||||
|
created_at = models.DateTimeField(default=timezone.now, editable=False)
|
||||||
|
expires_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
created_by = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
on_delete=models.SET_NULL,
|
||||||
|
related_name="server_enrollment_tokens",
|
||||||
|
)
|
||||||
|
used_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
server = models.ForeignKey(
|
||||||
|
Server, null=True, blank=True, on_delete=models.SET_NULL, related_name="enrollment_tokens"
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = "Enrollment token"
|
||||||
|
verbose_name_plural = "Enrollment tokens"
|
||||||
|
indexes = [
|
||||||
|
models.Index(fields=["created_at"], name="servers_enroll_created_idx"),
|
||||||
|
models.Index(fields=["used_at"], name="servers_enroll_used_idx"),
|
||||||
|
]
|
||||||
|
ordering = ["-created_at"]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.token[:8]}... ({'used' if self.used_at else 'unused'})"
|
||||||
|
|
||||||
|
def ensure_token(self) -> None:
|
||||||
|
if not self.token:
|
||||||
|
self.token = secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
def is_valid(self) -> bool:
|
||||||
|
if self.used_at:
|
||||||
|
return False
|
||||||
|
if self.expires_at and self.expires_at <= timezone.now():
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def mark_used(self, server: Server) -> None:
|
||||||
|
self.used_at = timezone.now()
|
||||||
|
self.server = server
|
||||||
|
|
||||||
|
def save(self, *args, **kwargs):
|
||||||
|
self.ensure_token()
|
||||||
|
super().save(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class AgentCertificateAuthority(models.Model):
|
||||||
|
name = models.CharField(max_length=128, default="Keywarden Agent CA")
|
||||||
|
cert_pem = models.TextField()
|
||||||
|
key_pem = models.TextField()
|
||||||
|
fingerprint = models.CharField(max_length=128, blank=True)
|
||||||
|
serial = models.CharField(max_length=64, blank=True)
|
||||||
|
created_at = models.DateTimeField(default=timezone.now, editable=False)
|
||||||
|
revoked_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
is_active = models.BooleanField(default=True, db_index=True)
|
||||||
|
created_by = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
on_delete=models.SET_NULL,
|
||||||
|
related_name="agent_certificate_authorities",
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = "Agent certificate authority"
|
||||||
|
verbose_name_plural = "Agent certificate authorities"
|
||||||
|
ordering = ["-created_at"]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
status = "active" if self.is_active and not self.revoked_at else "revoked"
|
||||||
|
return f"{self.name} ({status})"
|
||||||
|
|
||||||
|
def revoke(self) -> None:
|
||||||
|
self.is_active = False
|
||||||
|
self.revoked_at = timezone.now()
|
||||||
|
|
||||||
|
def ensure_material(self) -> None:
|
||||||
|
if self.cert_pem and self.key_pem:
|
||||||
|
return
|
||||||
|
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, self.name)])
|
||||||
|
now = datetime.utcnow()
|
||||||
|
cert = (
|
||||||
|
x509.CertificateBuilder()
|
||||||
|
.subject_name(subject)
|
||||||
|
.issuer_name(subject)
|
||||||
|
.public_key(key.public_key())
|
||||||
|
.serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now - timedelta(minutes=5))
|
||||||
|
.not_valid_after(now + timedelta(days=3650))
|
||||||
|
.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
|
||||||
|
.sign(key, hashes.SHA256())
|
||||||
|
)
|
||||||
|
cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
|
||||||
|
key_pem = key.private_bytes(
|
||||||
|
encoding=serialization.Encoding.PEM,
|
||||||
|
format=serialization.PrivateFormat.TraditionalOpenSSL,
|
||||||
|
encryption_algorithm=serialization.NoEncryption(),
|
||||||
|
).decode("utf-8")
|
||||||
|
self.cert_pem = cert_pem
|
||||||
|
self.key_pem = key_pem
|
||||||
|
self.fingerprint = cert.fingerprint(hashes.SHA256()).hex()
|
||||||
|
self.serial = format(cert.serial_number, "x")
|
||||||
|
|
||||||
|
|
||||||
|
class ServerAccount(models.Model):
|
||||||
|
server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name="accounts")
|
||||||
|
user = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="server_accounts"
|
||||||
|
)
|
||||||
|
system_username = models.CharField(max_length=128)
|
||||||
|
is_present = models.BooleanField(default=False, db_index=True)
|
||||||
|
last_synced_at = models.DateTimeField(default=timezone.now, editable=False)
|
||||||
|
created_at = models.DateTimeField(default=timezone.now, editable=False)
|
||||||
|
updated_at = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = "Server account"
|
||||||
|
verbose_name_plural = "Server accounts"
|
||||||
|
constraints = [
|
||||||
|
models.UniqueConstraint(fields=["server", "user"], name="unique_server_account")
|
||||||
|
]
|
||||||
|
indexes = [
|
||||||
|
models.Index(fields=["server", "user"], name="servers_account_user_idx"),
|
||||||
|
models.Index(fields=["server", "is_present"], name="servers_account_present_idx"),
|
||||||
|
]
|
||||||
|
ordering = ["server_id", "user_id"]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.system_username} ({self.server_id})"
|
||||||
|
|||||||
14
app/apps/servers/signals.py
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.db.models.signals import post_save
|
||||||
|
from django.dispatch import receiver
|
||||||
|
|
||||||
|
from apps.core.rbac import assign_default_object_permissions
|
||||||
|
from .models import Server
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(post_save, sender=Server)
|
||||||
|
def assign_server_perms(sender, instance: Server, created: bool, **kwargs) -> None:
|
||||||
|
if not created:
|
||||||
|
return
|
||||||
|
assign_default_object_permissions(instance)
|
||||||
63
app/apps/servers/templates/servers/dashboard.html
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Servers • Keywarden{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="space-y-8">
|
||||||
|
|
||||||
|
{% if servers %}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{% for item in servers %}
|
||||||
|
<article class="group relative overflow-hidden rounded-2xl border border-gray-200 bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
|
||||||
|
<div class="flex items-start justify-between">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-600 text-white font-semibold">
|
||||||
|
{{ item.server.initial }}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 class="text-lg font-semibold text-gray-900">{{ item.server.display_name }}</h2>
|
||||||
|
<p class="text-xs text-gray-500">
|
||||||
|
{{ item.server.hostname|default:item.server.ipv4|default:item.server.ipv6|default:"Unassigned" }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span class="inline-flex items-center rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-700">Active</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<dl class="mt-4 space-y-2 text-sm text-gray-600">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>Access until</dt>
|
||||||
|
<dd class="font-medium text-gray-900">
|
||||||
|
{% if item.expires_at %}
|
||||||
|
{{ item.expires_at|date:"M j, Y H:i" }}
|
||||||
|
{% else %}
|
||||||
|
No expiry
|
||||||
|
{% endif %}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>Last accessed</dt>
|
||||||
|
<dd class="font-medium text-gray-900">
|
||||||
|
{% if item.last_accessed %}
|
||||||
|
{{ item.last_accessed|date:"M j, Y H:i" }}
|
||||||
|
{% else %}
|
||||||
|
—
|
||||||
|
{% endif %}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
<div class="mt-4 border-t border-gray-100 pt-3 text-xs text-gray-500">
|
||||||
|
<a href="{% url 'servers:detail' item.server.id %}" class="font-semibold text-purple-700 hover:text-purple-800">View details and logs</a>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="rounded-xl border border-dashed border-gray-300 bg-white p-10 text-center">
|
||||||
|
<h2 class="text-lg font-semibold text-gray-900">No server access yet</h2>
|
||||||
|
<p class="mt-2 text-sm text-gray-600">Request access to a server to see it here.</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
96
app/apps/servers/templates/servers/detail.html
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{{ server.display_name }} • Keywarden{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="space-y-8">
|
||||||
|
<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<div class="flex h-12 w-12 items-center justify-center rounded-xl bg-purple-600 text-white text-xl font-semibold">
|
||||||
|
{{ server.initial }}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight text-gray-900">{{ server.display_name }}</h1>
|
||||||
|
<p class="text-sm text-gray-600">
|
||||||
|
{{ server.hostname|default:server.ipv4|default:server.ipv6|default:"Unassigned" }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<a href="{% url 'servers:dashboard' %}" class="text-sm font-semibold text-purple-700 hover:text-purple-800">Back to servers</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="grid gap-4 lg:grid-cols-3">
|
||||||
|
<div class="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm lg:col-span-2">
|
||||||
|
<h2 class="text-lg font-semibold text-gray-900">Access</h2>
|
||||||
|
<dl class="mt-4 space-y-3 text-sm text-gray-600">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>Access until</dt>
|
||||||
|
<dd class="font-medium text-gray-900">
|
||||||
|
{% if expires_at %}
|
||||||
|
{{ expires_at|date:"M j, Y H:i" }}
|
||||||
|
{% else %}
|
||||||
|
No expiry
|
||||||
|
{% endif %}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>Account name</dt>
|
||||||
|
<dd class="font-medium text-gray-900">
|
||||||
|
{% if system_username %}
|
||||||
|
{{ system_username }}
|
||||||
|
{% else %}
|
||||||
|
Unknown
|
||||||
|
{% endif %}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>Certificate</dt>
|
||||||
|
<dd class="font-medium text-gray-900">
|
||||||
|
<span class="inline-flex items-center rounded-full border border-gray-200 bg-gray-50 px-2 py-1 text-xs font-semibold text-gray-500">
|
||||||
|
Download coming soon
|
||||||
|
</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>Last accessed</dt>
|
||||||
|
<dd class="font-medium text-gray-900">
|
||||||
|
{% if last_accessed %}
|
||||||
|
{{ last_accessed|date:"M j, Y H:i" }}
|
||||||
|
{% else %}
|
||||||
|
—
|
||||||
|
{% endif %}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||||
|
<h2 class="text-lg font-semibold text-gray-900">Server details</h2>
|
||||||
|
<dl class="mt-4 space-y-3 text-sm text-gray-600">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>Hostname</dt>
|
||||||
|
<dd class="font-medium text-gray-900">{{ server.hostname|default:"—" }}</dd>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>IPv4</dt>
|
||||||
|
<dd class="font-medium text-gray-900">{{ server.ipv4|default:"—" }}</dd>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<dt>IPv6</dt>
|
||||||
|
<dd class="font-medium text-gray-900">{{ server.ipv6|default:"—" }}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<h2 class="text-lg font-semibold text-gray-900">Logs</h2>
|
||||||
|
<span class="text-xs font-semibold text-gray-500">Placeholder</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-4 rounded-xl border border-dashed border-gray-200 bg-gray-50 p-6 text-center text-sm text-gray-600">
|
||||||
|
Logs will appear here once collection is enabled for this server.
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
10
app/apps/servers/urls.py
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from . import views
|
||||||
|
|
||||||
|
app_name = "servers"
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("", views.dashboard, name="dashboard"),
|
||||||
|
path("<int:server_id>/", views.detail, name="detail"),
|
||||||
|
]
|
||||||
89
app/apps/servers/views.py
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.contrib.auth.decorators import login_required
|
||||||
|
from django.db.models import Q
|
||||||
|
from django.http import Http404
|
||||||
|
from django.shortcuts import render
|
||||||
|
from django.utils import timezone
|
||||||
|
from guardian.shortcuts import get_objects_for_user, get_perms
|
||||||
|
|
||||||
|
from apps.access.models import AccessRequest
|
||||||
|
from apps.servers.models import Server, ServerAccount
|
||||||
|
|
||||||
|
|
||||||
|
@login_required(login_url="/accounts/login/")
|
||||||
|
def dashboard(request):
|
||||||
|
now = timezone.now()
|
||||||
|
server_qs = get_objects_for_user(
|
||||||
|
request.user,
|
||||||
|
"servers.view_server",
|
||||||
|
klass=Server,
|
||||||
|
accept_global_perms=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
access_qs = (
|
||||||
|
AccessRequest.objects.select_related("server")
|
||||||
|
.filter(
|
||||||
|
requester=request.user,
|
||||||
|
status=AccessRequest.Status.APPROVED,
|
||||||
|
)
|
||||||
|
.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
|
||||||
|
)
|
||||||
|
expires_map = {}
|
||||||
|
for access in access_qs:
|
||||||
|
expires_at = access.expires_at
|
||||||
|
if access.server_id not in expires_map:
|
||||||
|
expires_map[access.server_id] = expires_at
|
||||||
|
continue
|
||||||
|
current = expires_map[access.server_id]
|
||||||
|
if current is None:
|
||||||
|
continue
|
||||||
|
if expires_at is None or expires_at > current:
|
||||||
|
expires_map[access.server_id] = expires_at
|
||||||
|
|
||||||
|
servers = [
|
||||||
|
{
|
||||||
|
"server": server,
|
||||||
|
"expires_at": expires_map.get(server.id),
|
||||||
|
"last_accessed": None,
|
||||||
|
}
|
||||||
|
for server in server_qs
|
||||||
|
]
|
||||||
|
|
||||||
|
context = {
|
||||||
|
"servers": servers,
|
||||||
|
}
|
||||||
|
return render(request, "servers/dashboard.html", context)
|
||||||
|
|
||||||
|
|
||||||
|
@login_required(login_url="/accounts/login/")
|
||||||
|
def detail(request, server_id: int):
|
||||||
|
now = timezone.now()
|
||||||
|
try:
|
||||||
|
server = Server.objects.get(id=server_id)
|
||||||
|
except Server.DoesNotExist:
|
||||||
|
raise Http404("Server not found")
|
||||||
|
if "view_server" not in get_perms(request.user, server):
|
||||||
|
raise Http404("Server not found")
|
||||||
|
|
||||||
|
access = (
|
||||||
|
AccessRequest.objects.filter(
|
||||||
|
requester=request.user,
|
||||||
|
server_id=server_id,
|
||||||
|
status=AccessRequest.Status.APPROVED,
|
||||||
|
)
|
||||||
|
.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
|
||||||
|
.order_by("-requested_at")
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
|
||||||
|
account = ServerAccount.objects.filter(server=server, user=request.user).first()
|
||||||
|
context = {
|
||||||
|
"server": server,
|
||||||
|
"expires_at": access.expires_at if access else None,
|
||||||
|
"last_accessed": None,
|
||||||
|
"account_present": account.is_present if account else None,
|
||||||
|
"account_synced_at": account.last_synced_at if account else None,
|
||||||
|
"system_username": account.system_username if account else None,
|
||||||
|
}
|
||||||
|
return render(request, "servers/detail.html", context)
|
||||||
@@ -1,6 +1,31 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
|
DOMAIN="${KEYWARDEN_DOMAIN:-localhost}"
|
||||||
|
CERT_DIR="/etc/nginx/certs"
|
||||||
|
NGINX_TEMPLATE="/etc/nginx/nginx.conf.template"
|
||||||
|
NGINX_CONF="/etc/nginx/nginx.conf"
|
||||||
|
|
||||||
|
# Replaces server_name in nginx.conf with $KEYWARDEN_DOMAIN
|
||||||
|
if [ -f "$NGINX_TEMPLATE" ]; then
|
||||||
|
ESCAPED_DOMAIN=$(printf '%s' "$DOMAIN" | sed 's/[&/]/\\&/g')
|
||||||
|
sed "s/__SERVER_NAME__/${ESCAPED_DOMAIN}/g" "$NGINX_TEMPLATE" > "$NGINX_CONF"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Creates self-signed certs using mkcert $KEYWARDEN_DOMAIN, and renaming them.
|
||||||
|
if [ ! -f "$CERT_DIR/certificate.pem" ] || [ ! -f "$CERT_DIR/key.pem" ]; then
|
||||||
|
mkdir -p "$CERT_DIR"
|
||||||
|
if command -v mkcert >/dev/null 2>&1; then
|
||||||
|
mkcert -install >/dev/null 2>&1 || true
|
||||||
|
mkcert -cert-file "$CERT_DIR/certificate.pem" -key-file "$CERT_DIR/key.pem" "$DOMAIN"
|
||||||
|
else
|
||||||
|
openssl req -x509 -nodes -newkey rsa:2048 -days 365 \
|
||||||
|
-subj "/CN=$DOMAIN" \
|
||||||
|
-keyout "$CERT_DIR/key.pem" \
|
||||||
|
-out "$CERT_DIR/certificate.pem"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# Build Tailwind CSS (best-effort; skip if not configured)
|
# Build Tailwind CSS (best-effort; skip if not configured)
|
||||||
python manage.py tailwind install || true
|
python manage.py tailwind install || true
|
||||||
python manage.py tailwind build || true
|
python manage.py tailwind build || true
|
||||||
@@ -12,4 +37,3 @@ python manage.py migrate --noinput
|
|||||||
python manage.py ensure_admin
|
python manage.py ensure_admin
|
||||||
|
|
||||||
exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
|
exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from .celery import app as celery_app
|
||||||
|
|
||||||
|
__all__ = ("celery_app",)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
|
import inspect
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
from ninja import NinjaAPI, Router, Schema
|
from ninja import NinjaAPI, Router, Schema, Redoc
|
||||||
from ninja.security import django_auth
|
from ninja.security import django_auth
|
||||||
|
|
||||||
from .security import JWTAuth
|
from .security import JWTAuth
|
||||||
@@ -14,34 +15,43 @@ from .routers.access import build_router as build_access_router
|
|||||||
from .routers.telemetry import build_router as build_telemetry_router
|
from .routers.telemetry import build_router as build_telemetry_router
|
||||||
from .routers.agent import build_router as build_agent_router
|
from .routers.agent import build_router as build_agent_router
|
||||||
|
|
||||||
|
from django.contrib.admin.views.decorators import staff_member_required
|
||||||
|
|
||||||
def register_routers(target_api: NinjaAPI) -> None:
|
def register_routers(target_api: NinjaAPI) -> None:
|
||||||
target_api.add_router("/system", build_system_router(), tags=["system"])
|
target_api.add_router("/system", build_system_router(), tags=["System"])
|
||||||
target_api.add_router("/user", build_accounts_router(), tags=["user"])
|
target_api.add_router("/user", build_accounts_router(), tags=["Account Context"])
|
||||||
target_api.add_router("/audit", build_audit_router(), tags=["audit"])
|
target_api.add_router("/audit", build_audit_router(), tags=["Audit Logging"])
|
||||||
target_api.add_router("/servers", build_servers_router(), tags=["servers"])
|
target_api.add_router("/servers", build_servers_router(), tags=["Servers"])
|
||||||
target_api.add_router("/users", build_users_router(), tags=["users"])
|
target_api.add_router("/users", build_users_router(), tags=["User Directory"])
|
||||||
target_api.add_router("/keys", build_keys_router(), tags=["keys"])
|
target_api.add_router("/keys", build_keys_router(), tags=["SSH Keys"])
|
||||||
target_api.add_router("/access-requests", build_access_router(), tags=["access"])
|
target_api.add_router("/access-requests", build_access_router(), tags=["Access Requests"])
|
||||||
target_api.add_router("/telemetry", build_telemetry_router(), tags=["telemetry"])
|
target_api.add_router("/telemetry", build_telemetry_router(), tags=["Telemetry"])
|
||||||
target_api.add_router("/agent", build_agent_router(), tags=["agent"])
|
target_api.add_router("/agent", build_agent_router(), tags=["Agent"])
|
||||||
|
|
||||||
|
|
||||||
api = NinjaAPI(
|
def build_api(**kwargs) -> NinjaAPI:
|
||||||
|
if "csrf" in inspect.signature(NinjaAPI).parameters:
|
||||||
|
return NinjaAPI(csrf=True, **kwargs)
|
||||||
|
return NinjaAPI(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
api = build_api(
|
||||||
title="Keywarden API",
|
title="Keywarden API",
|
||||||
version="1.0.0",
|
version="1.0.0",
|
||||||
description="Authenticated API for internal app use and external clients.",
|
description="Authenticated API for internal app use and external clients.",
|
||||||
auth=[django_auth, JWTAuth()],
|
auth=[django_auth, JWTAuth()],
|
||||||
csrf=True, # enforce CSRF for session-authenticated unsafe requests
|
docs=Redoc(),
|
||||||
|
docs_decorator=staff_member_required,
|
||||||
)
|
)
|
||||||
register_routers(api)
|
register_routers(api)
|
||||||
|
|
||||||
api_v1 = NinjaAPI(
|
api_v1 = build_api(
|
||||||
title="Keywarden API",
|
title="Keywarden API",
|
||||||
version="1.0.0",
|
version="1.0.0",
|
||||||
description="Authenticated API for internal app use and external clients.",
|
description="Authenticated API for internal app use and external clients.",
|
||||||
auth=[django_auth, JWTAuth()],
|
auth=[django_auth, JWTAuth()],
|
||||||
csrf=True,
|
|
||||||
urls_namespace="api-v1",
|
urls_namespace="api-v1",
|
||||||
|
docs=Redoc(),
|
||||||
|
docs_decorator=staff_member_required,
|
||||||
)
|
)
|
||||||
register_routers(api_v1)
|
register_routers(api_v1)
|
||||||
|
|||||||
@@ -5,12 +5,15 @@ from typing import List, Optional
|
|||||||
|
|
||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
from guardian.shortcuts import get_objects_for_user
|
||||||
from ninja import Query, Router, Schema
|
from ninja import Query, Router, Schema
|
||||||
from ninja.errors import HttpError
|
from ninja.errors import HttpError
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
|
||||||
from apps.access.models import AccessRequest
|
from apps.access.models import AccessRequest
|
||||||
|
from apps.core.rbac import require_authenticated
|
||||||
from apps.servers.models import Server
|
from apps.servers.models import Server
|
||||||
|
from apps.access.permissions import sync_server_view_perm
|
||||||
|
|
||||||
|
|
||||||
class AccessRequestCreateIn(Schema):
|
class AccessRequestCreateIn(Schema):
|
||||||
@@ -44,16 +47,6 @@ class AccessQuery(Schema):
|
|||||||
requester_id: Optional[int] = None
|
requester_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
def _require_authenticated(request: HttpRequest) -> None:
|
|
||||||
if not getattr(request.user, "is_authenticated", False):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
|
|
||||||
|
|
||||||
def _is_admin(request: HttpRequest) -> bool:
|
|
||||||
user = request.user
|
|
||||||
return bool(getattr(user, "is_staff", False) or getattr(user, "is_superuser", False))
|
|
||||||
|
|
||||||
|
|
||||||
def _request_to_out(access_request: AccessRequest) -> AccessRequestOut:
|
def _request_to_out(access_request: AccessRequest) -> AccessRequestOut:
|
||||||
return AccessRequestOut(
|
return AccessRequestOut(
|
||||||
id=access_request.id,
|
id=access_request.id,
|
||||||
@@ -68,19 +61,39 @@ def _request_to_out(access_request: AccessRequest) -> AccessRequestOut:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _has_global_perm(request: HttpRequest, perm: str) -> bool:
|
||||||
|
user = request.user
|
||||||
|
return bool(user and user.has_perm(perm))
|
||||||
|
|
||||||
|
|
||||||
def build_router() -> Router:
|
def build_router() -> Router:
|
||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
@router.get("/", response=List[AccessRequestOut])
|
@router.get("/", response=List[AccessRequestOut])
|
||||||
def list_requests(request: HttpRequest, filters: AccessQuery = Query(...)):
|
def list_requests(request: HttpRequest, filters: AccessQuery = Query(...)):
|
||||||
"""List access requests for the user, or all if admin."""
|
"""List access requests with pagination and filters.
|
||||||
_require_authenticated(request)
|
|
||||||
qs = AccessRequest.objects.order_by("-requested_at")
|
Auth: required.
|
||||||
if _is_admin(request):
|
Permissions:
|
||||||
if filters.requester_id:
|
- If user has global `access.view_accessrequest`, returns all requests.
|
||||||
qs = qs.filter(requester_id=filters.requester_id)
|
- Otherwise, returns only objects with `access.view_accessrequest` object permission.
|
||||||
|
Filters: status, server_id, requester_id (requester_id is honored only with global view).
|
||||||
|
Rationale: powers the access request queue and auditing views.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
|
user = request.user
|
||||||
|
if _has_global_perm(request, "access.view_accessrequest"):
|
||||||
|
qs = AccessRequest.objects.all()
|
||||||
else:
|
else:
|
||||||
qs = qs.filter(requester=request.user)
|
qs = get_objects_for_user(
|
||||||
|
user,
|
||||||
|
"access.view_accessrequest",
|
||||||
|
klass=AccessRequest,
|
||||||
|
accept_global_perms=False,
|
||||||
|
)
|
||||||
|
qs = qs.order_by("-requested_at")
|
||||||
|
if filters.requester_id and _has_global_perm(request, "access.view_accessrequest"):
|
||||||
|
qs = qs.filter(requester_id=filters.requester_id)
|
||||||
if filters.status:
|
if filters.status:
|
||||||
qs = qs.filter(status=filters.status)
|
qs = qs.filter(status=filters.status)
|
||||||
if filters.server_id:
|
if filters.server_id:
|
||||||
@@ -90,8 +103,18 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.post("/", response=AccessRequestOut)
|
@router.post("/", response=AccessRequestOut)
|
||||||
def create_request(request: HttpRequest, payload: AccessRequestCreateIn):
|
def create_request(request: HttpRequest, payload: AccessRequestCreateIn):
|
||||||
"""Create a new access request for a server."""
|
"""Create a new access request for the current user.
|
||||||
_require_authenticated(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires global `access.add_accessrequest`.
|
||||||
|
Side effects: grants owner object perms on the new request.
|
||||||
|
Behavior: creates a pending access request; it does not grant access
|
||||||
|
until approved. Optional expires_at defines the requested access window.
|
||||||
|
Rationale: this is the entry point for delegating server access.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
|
if not request.user.has_perm("access.add_accessrequest"):
|
||||||
|
raise HttpError(403, "Forbidden")
|
||||||
try:
|
try:
|
||||||
server = Server.objects.get(id=payload.server_id)
|
server = Server.objects.get(id=payload.server_id)
|
||||||
except Server.DoesNotExist:
|
except Server.DoesNotExist:
|
||||||
@@ -110,28 +133,43 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/{request_id}", response=AccessRequestOut)
|
@router.get("/{request_id}", response=AccessRequestOut)
|
||||||
def get_request(request: HttpRequest, request_id: int):
|
def get_request(request: HttpRequest, request_id: int):
|
||||||
"""Get an access request if permitted."""
|
"""Get a single access request by id.
|
||||||
_require_authenticated(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `access.view_accessrequest` on the object.
|
||||||
|
Rationale: used for request detail views and approval workflows.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
try:
|
try:
|
||||||
access_request = AccessRequest.objects.get(id=request_id)
|
access_request = AccessRequest.objects.get(id=request_id)
|
||||||
except AccessRequest.DoesNotExist:
|
except AccessRequest.DoesNotExist:
|
||||||
raise HttpError(404, "Not Found")
|
raise HttpError(404, "Not Found")
|
||||||
if not _is_admin(request) and access_request.requester_id != request.user.id:
|
if not request.user.has_perm("access.view_accessrequest", access_request):
|
||||||
raise HttpError(403, "Forbidden")
|
raise HttpError(403, "Forbidden")
|
||||||
return _request_to_out(access_request)
|
return _request_to_out(access_request)
|
||||||
|
|
||||||
@router.patch("/{request_id}", response=AccessRequestOut)
|
@router.patch("/{request_id}", response=AccessRequestOut)
|
||||||
def update_request(request: HttpRequest, request_id: int, payload: AccessRequestUpdateIn):
|
def update_request(request: HttpRequest, request_id: int, payload: AccessRequestUpdateIn):
|
||||||
"""Update request status or expiry (admin or owner with restrictions)."""
|
"""Update request status or expiry.
|
||||||
_require_authenticated(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `access.change_accessrequest` on the object.
|
||||||
|
Rules:
|
||||||
|
- Admin/operator (global change) can set status to approved/denied/revoked/cancelled and
|
||||||
|
update expires_at.
|
||||||
|
- Non-admin can only set status to cancelled, and only while pending.
|
||||||
|
Side effects: updates object permissions for server visibility when
|
||||||
|
approvals or revocations occur.
|
||||||
|
Rationale: this is the core approval/denial path for access control.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
try:
|
try:
|
||||||
access_request = AccessRequest.objects.get(id=request_id)
|
access_request = AccessRequest.objects.get(id=request_id)
|
||||||
except AccessRequest.DoesNotExist:
|
except AccessRequest.DoesNotExist:
|
||||||
raise HttpError(404, "Not Found")
|
raise HttpError(404, "Not Found")
|
||||||
is_admin = _is_admin(request)
|
if not request.user.has_perm("access.change_accessrequest", access_request):
|
||||||
is_owner = access_request.requester_id == request.user.id
|
|
||||||
if not is_admin and not is_owner:
|
|
||||||
raise HttpError(403, "Forbidden")
|
raise HttpError(403, "Forbidden")
|
||||||
|
is_admin = _has_global_perm(request, "access.change_accessrequest")
|
||||||
if payload.status is None and payload.expires_at is None:
|
if payload.status is None and payload.expires_at is None:
|
||||||
raise HttpError(422, {"detail": "No fields provided."})
|
raise HttpError(422, {"detail": "No fields provided."})
|
||||||
if payload.expires_at is not None:
|
if payload.expires_at is not None:
|
||||||
@@ -162,21 +200,9 @@ def build_router() -> Router:
|
|||||||
else:
|
else:
|
||||||
access_request.decided_by = None
|
access_request.decided_by = None
|
||||||
access_request.save()
|
access_request.save()
|
||||||
|
sync_server_view_perm(access_request)
|
||||||
return _request_to_out(access_request)
|
return _request_to_out(access_request)
|
||||||
|
|
||||||
@router.delete("/{request_id}", response={204: None})
|
|
||||||
def delete_request(request: HttpRequest, request_id: int):
|
|
||||||
"""Delete an access request if permitted."""
|
|
||||||
_require_authenticated(request)
|
|
||||||
try:
|
|
||||||
access_request = AccessRequest.objects.get(id=request_id)
|
|
||||||
except AccessRequest.DoesNotExist:
|
|
||||||
raise HttpError(404, "Not Found")
|
|
||||||
if not _is_admin(request) and access_request.requester_id != request.user.id:
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
access_request.delete()
|
|
||||||
return 204, None
|
|
||||||
|
|
||||||
return router
|
return router
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from typing import Optional
|
|||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from ninja import Router, Schema
|
from ninja import Router, Schema
|
||||||
|
|
||||||
|
from apps.core.rbac import require_authenticated
|
||||||
|
|
||||||
class UserSchema(Schema):
|
class UserSchema(Schema):
|
||||||
id: int
|
id: int
|
||||||
@@ -19,7 +20,15 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/me", response=UserSchema)
|
@router.get("/me", response=UserSchema)
|
||||||
def me(request: HttpRequest):
|
def me(request: HttpRequest):
|
||||||
"""Return the current authenticated user's profile."""
|
"""Return the authenticated user's profile and role context.
|
||||||
|
|
||||||
|
Auth: required (session or JWT). Used by the UI to build navigation,
|
||||||
|
display the user identity, and decide which actions are enabled.
|
||||||
|
Fields: returns only the minimal identity and privilege flags needed
|
||||||
|
by the client; no secrets or permissions lists are exposed here.
|
||||||
|
Rationale: keeps the client-side state aligned with the session user.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
user = request.user
|
user = request.user
|
||||||
return {
|
return {
|
||||||
"id": user.id,
|
"id": user.id,
|
||||||
|
|||||||
@@ -1,17 +1,31 @@
|
|||||||
from __future__ import annotations
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
from django.db import models
|
from cryptography import x509
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||||
|
from django.conf import settings
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.core.validators import validate_ipv4_address, validate_ipv6_address
|
||||||
|
from django.db import IntegrityError, transaction
|
||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from ninja import Router, Schema
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
|
from ninja import Body, Router, Schema
|
||||||
from ninja.errors import HttpError
|
from ninja.errors import HttpError
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
from guardian.shortcuts import get_users_with_perms
|
||||||
|
|
||||||
from apps.access.models import AccessRequest
|
from apps.core.rbac import require_perms
|
||||||
from apps.keys.models import SSHKey
|
from apps.keys.models import SSHKey
|
||||||
from apps.servers.models import Server
|
from apps.servers.models import (
|
||||||
|
AgentCertificateAuthority,
|
||||||
|
EnrollmentToken,
|
||||||
|
Server,
|
||||||
|
ServerAccount,
|
||||||
|
hostname_validator,
|
||||||
|
)
|
||||||
from apps.telemetry.models import TelemetryEvent
|
from apps.telemetry.models import TelemetryEvent
|
||||||
|
|
||||||
|
|
||||||
@@ -23,63 +37,208 @@ class AuthorizedKeyOut(Schema):
|
|||||||
fingerprint: str
|
fingerprint: str
|
||||||
|
|
||||||
|
|
||||||
|
class AccountKeyOut(Schema):
|
||||||
|
public_key: str
|
||||||
|
fingerprint: str
|
||||||
|
|
||||||
|
|
||||||
|
class AccountAccessOut(Schema):
|
||||||
|
user_id: int
|
||||||
|
username: str
|
||||||
|
email: str
|
||||||
|
keys: List[AccountKeyOut]
|
||||||
|
|
||||||
|
|
||||||
|
class AccountSyncIn(Schema):
|
||||||
|
user_id: int
|
||||||
|
system_username: str
|
||||||
|
present: bool
|
||||||
|
|
||||||
|
|
||||||
class SyncReportIn(Schema):
|
class SyncReportIn(Schema):
|
||||||
applied_count: int = Field(default=0, ge=0)
|
applied_count: int = Field(default=0, ge=0)
|
||||||
revoked_count: int = Field(default=0, ge=0)
|
revoked_count: int = Field(default=0, ge=0)
|
||||||
message: Optional[str] = None
|
message: Optional[str] = None
|
||||||
metadata: dict = Field(default_factory=dict)
|
metadata: dict = Field(default_factory=dict)
|
||||||
|
accounts: List[AccountSyncIn] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
class SyncReportOut(Schema):
|
class SyncReportOut(Schema):
|
||||||
status: str
|
status: str
|
||||||
|
|
||||||
|
|
||||||
def _require_admin(request: HttpRequest) -> None:
|
class AgentEnrollIn(Schema):
|
||||||
user = request.user
|
token: str
|
||||||
if not getattr(user, "is_authenticated", False):
|
csr_pem: str
|
||||||
raise HttpError(403, "Forbidden")
|
host: Optional[str] = None
|
||||||
if not (user.is_staff or user.is_superuser):
|
ipv4: Optional[str] = None
|
||||||
raise HttpError(403, "Forbidden")
|
ipv6: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class AgentEnrollOut(Schema):
|
||||||
|
server_id: str
|
||||||
|
client_cert_pem: str
|
||||||
|
ca_cert_pem: str
|
||||||
|
|
||||||
|
|
||||||
|
class LogEventIn(Schema):
|
||||||
|
timestamp: str
|
||||||
|
category: str
|
||||||
|
event_type: str
|
||||||
|
unit: Optional[str] = None
|
||||||
|
priority: Optional[str] = None
|
||||||
|
hostname: Optional[str] = None
|
||||||
|
username: Optional[str] = None
|
||||||
|
principal: Optional[str] = None
|
||||||
|
source_ip: Optional[str] = None
|
||||||
|
session_id: Optional[str] = None
|
||||||
|
message: Optional[str] = None
|
||||||
|
raw: Optional[str] = None
|
||||||
|
fields: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
|
class LogIngestOut(Schema):
|
||||||
|
status: str
|
||||||
|
accepted: int
|
||||||
|
|
||||||
|
|
||||||
|
class AgentHeartbeatIn(Schema):
|
||||||
|
host: Optional[str] = None
|
||||||
|
ipv4: Optional[str] = None
|
||||||
|
ipv6: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
def build_router() -> Router:
|
def build_router() -> Router:
|
||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
|
@router.post("/enroll", response=AgentEnrollOut, auth=None)
|
||||||
|
@csrf_exempt
|
||||||
|
def enroll_agent(request: HttpRequest, payload: AgentEnrollIn = Body(...)):
|
||||||
|
"""Enroll a server agent using a one-time enrollment token.
|
||||||
|
|
||||||
|
Auth: token only (no session/JWT); mTLS is not yet available until
|
||||||
|
enrollment completes.
|
||||||
|
Inputs: enrollment token + CSR from the agent, optional host/IP hints.
|
||||||
|
Behavior:
|
||||||
|
- Creates a Server record (agent is the source of truth for host/IP).
|
||||||
|
- Marks the token as used (single-use).
|
||||||
|
- Signs the CSR with the active Agent CA and returns client cert + CA.
|
||||||
|
Rationale: this is the only supported server onboarding flow. If this
|
||||||
|
endpoint is removed, agents cannot bootstrap mTLS credentials.
|
||||||
|
"""
|
||||||
|
token_value = (payload.token or "").strip()
|
||||||
|
if not token_value:
|
||||||
|
raise HttpError(422, "Token required")
|
||||||
|
try:
|
||||||
|
token = EnrollmentToken.objects.get(token=token_value)
|
||||||
|
except EnrollmentToken.DoesNotExist:
|
||||||
|
raise HttpError(403, "Invalid token")
|
||||||
|
if not token.is_valid():
|
||||||
|
raise HttpError(403, "Token expired or already used")
|
||||||
|
|
||||||
|
host = (payload.host or "").strip()[:253]
|
||||||
|
display_name = host or "server"
|
||||||
|
hostname = None
|
||||||
|
if host:
|
||||||
|
try:
|
||||||
|
hostname_validator(host)
|
||||||
|
hostname = host
|
||||||
|
except ValidationError:
|
||||||
|
hostname = None
|
||||||
|
ipv4 = _normalize_ip(payload.ipv4, 4)
|
||||||
|
ipv6 = _normalize_ip(payload.ipv6, 6)
|
||||||
|
|
||||||
|
csr = _load_csr((payload.csr_pem or "").strip())
|
||||||
|
try:
|
||||||
|
with transaction.atomic():
|
||||||
|
server = Server.objects.create(
|
||||||
|
display_name=display_name,
|
||||||
|
hostname=hostname,
|
||||||
|
ipv4=ipv4,
|
||||||
|
ipv6=ipv6,
|
||||||
|
)
|
||||||
|
token.mark_used(server)
|
||||||
|
token.save(update_fields=["used_at", "server"])
|
||||||
|
cert_pem, ca_pem, fingerprint, serial = _issue_client_cert(csr, host, server.id)
|
||||||
|
server.agent_enrolled_at = timezone.now()
|
||||||
|
server.agent_cert_fingerprint = fingerprint
|
||||||
|
server.agent_cert_serial = serial
|
||||||
|
server.save(update_fields=["agent_enrolled_at", "agent_cert_fingerprint", "agent_cert_serial"])
|
||||||
|
except IntegrityError:
|
||||||
|
raise HttpError(409, "Server already enrolled")
|
||||||
|
|
||||||
|
return AgentEnrollOut(
|
||||||
|
server_id=str(server.id),
|
||||||
|
client_cert_pem=cert_pem,
|
||||||
|
ca_cert_pem=ca_pem,
|
||||||
|
)
|
||||||
|
|
||||||
@router.get("/servers/{server_id}/authorized-keys", response=List[AuthorizedKeyOut])
|
@router.get("/servers/{server_id}/authorized-keys", response=List[AuthorizedKeyOut])
|
||||||
def authorized_keys(request: HttpRequest, server_id: int):
|
def authorized_keys(request: HttpRequest, server_id: int):
|
||||||
"""Return authorized public keys for a server (admin only)."""
|
"""Resolve the effective authorized_keys list for a server.
|
||||||
_require_admin(request)
|
|
||||||
try:
|
Auth: required (admin/operator via API).
|
||||||
server = Server.objects.get(id=server_id)
|
Permissions: requires view access to servers and keys.
|
||||||
except Server.DoesNotExist:
|
Behavior: uses server object permissions + active SSH keys to produce
|
||||||
raise HttpError(404, "Server not found")
|
the exact key list the agent should deploy to the server.
|
||||||
now = timezone.now()
|
Rationale: this is the policy enforcement point for per-user access.
|
||||||
access_qs = AccessRequest.objects.select_related("requester").filter(
|
"""
|
||||||
server=server,
|
require_perms(
|
||||||
status=AccessRequest.Status.APPROVED,
|
request,
|
||||||
|
"servers.view_server",
|
||||||
|
"keys.view_sshkey",
|
||||||
)
|
)
|
||||||
access_qs = access_qs.filter(models.Q(expires_at__isnull=True) | models.Q(expires_at__gt=now))
|
server = _get_server_or_404(server_id)
|
||||||
users = [req.requester for req in access_qs if req.requester and req.requester.is_active]
|
users = _resolve_access_users(server)
|
||||||
keys = SSHKey.objects.select_related("user").filter(
|
key_map = _key_map_for_users(users)
|
||||||
user__in=users,
|
output: list[AuthorizedKeyOut] = []
|
||||||
is_active=True,
|
for user in users:
|
||||||
revoked_at__isnull=True,
|
for key in key_map.get(user.id, []):
|
||||||
)
|
output.append(
|
||||||
return [
|
|
||||||
AuthorizedKeyOut(
|
AuthorizedKeyOut(
|
||||||
user_id=key.user_id,
|
user_id=user.id,
|
||||||
username=key.user.username,
|
username=user.username,
|
||||||
email=key.user.email or "",
|
email=user.email or "",
|
||||||
public_key=key.public_key,
|
public_key=key.public_key,
|
||||||
fingerprint=key.fingerprint,
|
fingerprint=key.fingerprint,
|
||||||
)
|
)
|
||||||
for key in keys
|
)
|
||||||
|
return output
|
||||||
|
|
||||||
|
@router.get("/servers/{server_id}/accounts", response=List[AccountAccessOut], auth=None)
|
||||||
|
def account_access(request: HttpRequest, server_id: int):
|
||||||
|
"""List accounts that should exist on a server.
|
||||||
|
|
||||||
|
Auth: mTLS expected at the edge (no session/JWT).
|
||||||
|
Behavior: resolves active users with server object perms and their keys.
|
||||||
|
Rationale: drives agent-side account provisioning.
|
||||||
|
"""
|
||||||
|
server = _get_server_or_404(server_id)
|
||||||
|
users = _resolve_access_users(server)
|
||||||
|
key_map = _key_map_for_users(users)
|
||||||
|
return [
|
||||||
|
AccountAccessOut(
|
||||||
|
user_id=user.id,
|
||||||
|
username=user.username,
|
||||||
|
email=user.email or "",
|
||||||
|
keys=[
|
||||||
|
AccountKeyOut(public_key=key.public_key, fingerprint=key.fingerprint)
|
||||||
|
for key in key_map.get(user.id, [])
|
||||||
|
],
|
||||||
|
)
|
||||||
|
for user in users
|
||||||
]
|
]
|
||||||
|
|
||||||
@router.post("/servers/{server_id}/sync-report", response=SyncReportOut)
|
@router.post("/servers/{server_id}/sync-report", response=SyncReportOut, auth=None)
|
||||||
def sync_report(request: HttpRequest, server_id: int, payload: SyncReportIn):
|
@csrf_exempt
|
||||||
"""Record an agent sync report for a server (admin only)."""
|
def sync_report(request: HttpRequest, server_id: int, payload: SyncReportIn = Body(...)):
|
||||||
_require_admin(request)
|
"""Record an agent sync report for a server.
|
||||||
|
|
||||||
|
Auth: mTLS expected at the edge (no session/JWT).
|
||||||
|
Behavior: stores a telemetry event with counts of applied/revoked keys.
|
||||||
|
Rationale: provides an audit trail of enforcement actions without
|
||||||
|
requiring full log ingestion for every sync cycle.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
server = Server.objects.get(id=server_id)
|
server = Server.objects.get(id=server_id)
|
||||||
except Server.DoesNotExist:
|
except Server.DoesNotExist:
|
||||||
@@ -96,9 +255,194 @@ def build_router() -> Router:
|
|||||||
**(payload.metadata or {}),
|
**(payload.metadata or {}),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
if payload.accounts:
|
||||||
|
_update_server_accounts(server, payload.accounts)
|
||||||
|
return SyncReportOut(status="ok")
|
||||||
|
|
||||||
|
@router.post("/servers/{server_id}/logs", response=LogIngestOut, auth=None)
|
||||||
|
@csrf_exempt
|
||||||
|
def ingest_logs(request: HttpRequest, server_id: int, payload: List[LogEventIn] = Body(...)):
|
||||||
|
"""Accept log batches from agents for audit collection.
|
||||||
|
|
||||||
|
Auth: mTLS expected at the edge (no session/JWT).
|
||||||
|
Behavior: accepts structured log events for later storage and indexing.
|
||||||
|
Storage: raw logs are persisted separately per-server (SQLite shards),
|
||||||
|
not in the primary Postgres database.
|
||||||
|
Rationale: this is the ingestion pipe for security audit logging.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
Server.objects.get(id=server_id)
|
||||||
|
except Server.DoesNotExist:
|
||||||
|
raise HttpError(404, "Server not found")
|
||||||
|
# TODO: enqueue to Valkey and persist to SQLite slices.
|
||||||
|
return LogIngestOut(status="accepted", accepted=len(payload))
|
||||||
|
|
||||||
|
@router.post("/servers/{server_id}/heartbeat", response=SyncReportOut, auth=None)
|
||||||
|
@csrf_exempt
|
||||||
|
def heartbeat(request: HttpRequest, server_id: int, payload: AgentHeartbeatIn = Body(...)):
|
||||||
|
"""Update server host metadata (hostname/IPs) reported by the agent.
|
||||||
|
|
||||||
|
Auth: mTLS expected at the edge (no session/JWT).
|
||||||
|
Behavior: updates hostname/IPv4/IPv6 when they change (e.g., DHCP).
|
||||||
|
Conflict: unique constraints are enforced; conflicts return 409.
|
||||||
|
Rationale: keeps the server inventory accurate without manual edits.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
server = Server.objects.get(id=server_id)
|
||||||
|
except Server.DoesNotExist:
|
||||||
|
raise HttpError(404, "Server not found")
|
||||||
|
updates: dict[str, str] = {}
|
||||||
|
host = (payload.host or "").strip()[:253]
|
||||||
|
if host:
|
||||||
|
try:
|
||||||
|
hostname_validator(host)
|
||||||
|
if server.hostname != host:
|
||||||
|
updates["hostname"] = host
|
||||||
|
except ValidationError:
|
||||||
|
pass
|
||||||
|
ipv4 = _normalize_ip(payload.ipv4, 4)
|
||||||
|
if ipv4 and server.ipv4 != ipv4:
|
||||||
|
updates["ipv4"] = ipv4
|
||||||
|
ipv6 = _normalize_ip(payload.ipv6, 6)
|
||||||
|
if ipv6 and server.ipv6 != ipv6:
|
||||||
|
updates["ipv6"] = ipv6
|
||||||
|
if updates:
|
||||||
|
for field, value in updates.items():
|
||||||
|
setattr(server, field, value)
|
||||||
|
try:
|
||||||
|
server.save(update_fields=list(updates.keys()))
|
||||||
|
except IntegrityError:
|
||||||
|
raise HttpError(409, "Server address already in use")
|
||||||
return SyncReportOut(status="ok")
|
return SyncReportOut(status="ok")
|
||||||
|
|
||||||
return router
|
return router
|
||||||
|
|
||||||
|
|
||||||
|
def _get_server_or_404(server_id: int) -> Server:
|
||||||
|
try:
|
||||||
|
return Server.objects.get(id=server_id)
|
||||||
|
except Server.DoesNotExist:
|
||||||
|
raise HttpError(404, "Server not found")
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_access_users(server: Server) -> list:
|
||||||
|
users = list(
|
||||||
|
get_users_with_perms(
|
||||||
|
server,
|
||||||
|
only_with_perms_in=["view_server"],
|
||||||
|
with_group_users=True,
|
||||||
|
with_superusers=False,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
active = [user for user in users if getattr(user, "is_active", False)]
|
||||||
|
return sorted(active, key=lambda user: (user.username or "", user.id))
|
||||||
|
|
||||||
|
|
||||||
|
def _key_map_for_users(users: list) -> dict[int, list[SSHKey]]:
|
||||||
|
if not users:
|
||||||
|
return {}
|
||||||
|
keys = SSHKey.objects.select_related("user").filter(
|
||||||
|
user__in=users,
|
||||||
|
is_active=True,
|
||||||
|
revoked_at__isnull=True,
|
||||||
|
)
|
||||||
|
key_map: dict[int, list[SSHKey]] = {}
|
||||||
|
for key in keys:
|
||||||
|
key_map.setdefault(key.user_id, []).append(key)
|
||||||
|
return key_map
|
||||||
|
|
||||||
|
|
||||||
|
def _update_server_accounts(server: Server, accounts: list[AccountSyncIn]) -> None:
|
||||||
|
user_ids = {account.user_id for account in accounts}
|
||||||
|
if not user_ids:
|
||||||
|
return
|
||||||
|
User = get_user_model()
|
||||||
|
users = {user.id: user for user in User.objects.filter(id__in=user_ids)}
|
||||||
|
now = timezone.now()
|
||||||
|
for account in accounts:
|
||||||
|
user = users.get(account.user_id)
|
||||||
|
if not user:
|
||||||
|
continue
|
||||||
|
ServerAccount.objects.update_or_create(
|
||||||
|
server=server,
|
||||||
|
user=user,
|
||||||
|
defaults={
|
||||||
|
"system_username": account.system_username,
|
||||||
|
"is_present": account.present,
|
||||||
|
"last_synced_at": now,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_agent_ca() -> tuple[x509.Certificate, object, str]:
|
||||||
|
ca = (
|
||||||
|
AgentCertificateAuthority.objects.filter(is_active=True, revoked_at__isnull=True)
|
||||||
|
.order_by("-created_at")
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if not ca:
|
||||||
|
raise HttpError(500, "Agent CA not configured")
|
||||||
|
try:
|
||||||
|
ca_cert = x509.load_pem_x509_certificate(ca.cert_pem.encode("utf-8"))
|
||||||
|
ca_key = serialization.load_pem_private_key(ca.key_pem.encode("utf-8"), password=None)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
raise HttpError(500, "Invalid agent CA material")
|
||||||
|
return ca_cert, ca_key, ca.cert_pem
|
||||||
|
|
||||||
|
|
||||||
|
def _load_csr(csr_pem: str) -> x509.CertificateSigningRequest:
|
||||||
|
try:
|
||||||
|
csr = x509.load_pem_x509_csr(csr_pem.encode("utf-8"))
|
||||||
|
except ValueError:
|
||||||
|
raise HttpError(422, "Invalid CSR")
|
||||||
|
if not csr.is_signature_valid:
|
||||||
|
raise HttpError(422, "Invalid CSR signature")
|
||||||
|
return csr
|
||||||
|
|
||||||
|
|
||||||
|
def _issue_client_cert(
|
||||||
|
csr: x509.CertificateSigningRequest, host: str | None, server_id: int
|
||||||
|
) -> tuple[str, str, str, str]:
|
||||||
|
ca_cert, ca_key, ca_pem = _load_agent_ca()
|
||||||
|
now = datetime.utcnow()
|
||||||
|
subject = csr.subject
|
||||||
|
if len(subject) == 0:
|
||||||
|
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, f"keywarden-agent-{server_id}")])
|
||||||
|
builder = (
|
||||||
|
x509.CertificateBuilder()
|
||||||
|
.subject_name(subject)
|
||||||
|
.issuer_name(ca_cert.subject)
|
||||||
|
.public_key(csr.public_key())
|
||||||
|
.serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now - timedelta(minutes=5))
|
||||||
|
.not_valid_after(now + timedelta(days=settings.KEYWARDEN_AGENT_CERT_VALIDITY_DAYS))
|
||||||
|
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
||||||
|
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False)
|
||||||
|
)
|
||||||
|
if host:
|
||||||
|
try:
|
||||||
|
hostname_validator(host)
|
||||||
|
builder = builder.add_extension(x509.SubjectAlternativeName([x509.DNSName(host)]), critical=False)
|
||||||
|
except ValidationError:
|
||||||
|
pass
|
||||||
|
cert = builder.sign(private_key=ca_key, algorithm=hashes.SHA256())
|
||||||
|
cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
|
||||||
|
fingerprint = cert.fingerprint(hashes.SHA256()).hex()
|
||||||
|
serial = format(cert.serial_number, "x")
|
||||||
|
return cert_pem, ca_pem, fingerprint, serial
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_ip(value: Optional[str], version: int) -> Optional[str]:
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
if version == 4:
|
||||||
|
validate_ipv4_address(value)
|
||||||
|
else:
|
||||||
|
validate_ipv6_address(value)
|
||||||
|
except ValidationError:
|
||||||
|
return None
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
router = build_router()
|
router = build_router()
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from django.http import HttpRequest
|
|||||||
from ninja import Query, Router, Schema
|
from ninja import Query, Router, Schema
|
||||||
|
|
||||||
from apps.audit.models import AuditEventType, AuditLog
|
from apps.audit.models import AuditEventType, AuditLog
|
||||||
|
from apps.core.rbac import require_perms
|
||||||
|
|
||||||
class AuditEventTypeSchema(Schema):
|
class AuditEventTypeSchema(Schema):
|
||||||
id: int
|
id: int
|
||||||
@@ -46,7 +47,15 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/event-types", response=List[AuditEventTypeSchema])
|
@router.get("/event-types", response=List[AuditEventTypeSchema])
|
||||||
def list_event_types(request: HttpRequest):
|
def list_event_types(request: HttpRequest):
|
||||||
"""List audit event types and their default severity."""
|
"""List audit event types used by the platform audit log.
|
||||||
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires global `audit.view_auditeventtype`.
|
||||||
|
Behavior: returns the canonical event taxonomy (key, title, severity).
|
||||||
|
Rationale: the admin UI and audit filters use this to map log entries
|
||||||
|
to human-readable categories and severity defaults.
|
||||||
|
"""
|
||||||
|
require_perms(request, "audit.view_auditeventtype")
|
||||||
qs: QuerySet[AuditEventType] = AuditEventType.objects.all()
|
qs: QuerySet[AuditEventType] = AuditEventType.objects.all()
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -61,7 +70,17 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/logs", response=List[AuditLogSchema])
|
@router.get("/logs", response=List[AuditLogSchema])
|
||||||
def list_logs(request: HttpRequest, filters: LogsQuery = Query(...)):
|
def list_logs(request: HttpRequest, filters: LogsQuery = Query(...)):
|
||||||
"""List audit logs with optional filters and pagination."""
|
"""List application audit log entries with filters and pagination.
|
||||||
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires global `audit.view_auditlog`.
|
||||||
|
Filters: severity, actor_id, event_type_key, source.
|
||||||
|
Pagination: limit + offset.
|
||||||
|
Scope: this is the Keywarden app audit trail (who changed what), not
|
||||||
|
the server OS log ingestion stream stored by the agent.
|
||||||
|
Rationale: used by the audit UI and for administrative forensics.
|
||||||
|
"""
|
||||||
|
require_perms(request, "audit.view_auditlog")
|
||||||
qs: QuerySet[AuditLog] = AuditLog.objects.select_related("event_type", "actor").all()
|
qs: QuerySet[AuditLog] = AuditLog.objects.select_related("event_type", "actor").all()
|
||||||
if filters.severity:
|
if filters.severity:
|
||||||
qs = qs.filter(severity=filters.severity)
|
qs = qs.filter(severity=filters.severity)
|
||||||
|
|||||||
@@ -7,10 +7,12 @@ from django.core.exceptions import ValidationError
|
|||||||
from django.db import IntegrityError
|
from django.db import IntegrityError
|
||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
from guardian.shortcuts import get_objects_for_user
|
||||||
from ninja import Query, Router, Schema
|
from ninja import Query, Router, Schema
|
||||||
from ninja.errors import HttpError
|
from ninja.errors import HttpError
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
|
||||||
|
from apps.core.rbac import require_authenticated
|
||||||
from apps.keys.models import SSHKey
|
from apps.keys.models import SSHKey
|
||||||
|
|
||||||
|
|
||||||
@@ -43,16 +45,6 @@ class KeysQuery(Schema):
|
|||||||
user_id: Optional[int] = None
|
user_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
def _require_authenticated(request: HttpRequest) -> None:
|
|
||||||
if not getattr(request.user, "is_authenticated", False):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
|
|
||||||
|
|
||||||
def _is_admin(request: HttpRequest) -> bool:
|
|
||||||
user = request.user
|
|
||||||
return bool(getattr(user, "is_staff", False) or getattr(user, "is_superuser", False))
|
|
||||||
|
|
||||||
|
|
||||||
def _key_to_out(key: SSHKey) -> KeyOut:
|
def _key_to_out(key: SSHKey) -> KeyOut:
|
||||||
return KeyOut(
|
return KeyOut(
|
||||||
id=key.id,
|
id=key.id,
|
||||||
@@ -67,33 +59,69 @@ def _key_to_out(key: SSHKey) -> KeyOut:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _has_global_perm(request: HttpRequest, perm: str) -> bool:
|
||||||
|
user = request.user
|
||||||
|
return bool(user and user.has_perm(perm))
|
||||||
|
|
||||||
|
|
||||||
def build_router() -> Router:
|
def build_router() -> Router:
|
||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
@router.get("/", response=List[KeyOut])
|
@router.get("/", response=List[KeyOut])
|
||||||
def list_keys(request: HttpRequest, filters: KeysQuery = Query(...)):
|
def list_keys(request: HttpRequest, filters: KeysQuery = Query(...)):
|
||||||
"""List SSH keys for the current user, or any user if admin."""
|
"""List SSH keys with pagination and filters.
|
||||||
_require_authenticated(request)
|
|
||||||
qs = SSHKey.objects.order_by("-created_at")
|
Auth: required.
|
||||||
if _is_admin(request):
|
Permissions:
|
||||||
if filters.user_id:
|
- If user has global `keys.view_sshkey`, returns all keys.
|
||||||
qs = qs.filter(user_id=filters.user_id)
|
- Otherwise, returns only objects with `keys.view_sshkey` object permission.
|
||||||
|
Filter: user_id (honored only with global view).
|
||||||
|
Rationale: powers the key inventory UI and lets admins audit key usage.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
|
user = request.user
|
||||||
|
if _has_global_perm(request, "keys.view_sshkey"):
|
||||||
|
qs = SSHKey.objects.all()
|
||||||
else:
|
else:
|
||||||
qs = qs.filter(user=request.user)
|
qs = get_objects_for_user(
|
||||||
|
user,
|
||||||
|
"keys.view_sshkey",
|
||||||
|
klass=SSHKey,
|
||||||
|
accept_global_perms=False,
|
||||||
|
)
|
||||||
|
qs = qs.order_by("-created_at")
|
||||||
|
if filters.user_id and _has_global_perm(request, "keys.view_sshkey"):
|
||||||
|
qs = qs.filter(user_id=filters.user_id)
|
||||||
qs = qs[filters.offset : filters.offset + filters.limit]
|
qs = qs[filters.offset : filters.offset + filters.limit]
|
||||||
return [_key_to_out(key) for key in qs]
|
return [_key_to_out(key) for key in qs]
|
||||||
|
|
||||||
@router.post("/", response=KeyOut)
|
@router.post("/", response=KeyOut)
|
||||||
def create_key(request: HttpRequest, payload: KeyCreateIn):
|
def create_key(request: HttpRequest, payload: KeyCreateIn):
|
||||||
"""Create an SSH public key for the current user (admin can specify user_id)."""
|
"""Create an SSH public key.
|
||||||
_require_authenticated(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires global `keys.add_sshkey`.
|
||||||
|
Rules:
|
||||||
|
- Default owner is the current user.
|
||||||
|
- If caller has global `keys.add_sshkey` and `keys.view_sshkey`, they may specify user_id.
|
||||||
|
Side effects: grants owner object perms on the new key.
|
||||||
|
Rationale: keys are the core authorization material synced to servers.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
|
if not request.user.has_perm("keys.add_sshkey"):
|
||||||
|
raise HttpError(403, "Forbidden")
|
||||||
|
is_admin = _has_global_perm(request, "keys.add_sshkey") and _has_global_perm(
|
||||||
|
request, "keys.view_sshkey"
|
||||||
|
)
|
||||||
owner = request.user
|
owner = request.user
|
||||||
if _is_admin(request) and payload.user_id:
|
if is_admin and payload.user_id:
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
try:
|
try:
|
||||||
owner = User.objects.get(id=payload.user_id)
|
owner = User.objects.get(id=payload.user_id)
|
||||||
except User.DoesNotExist:
|
except User.DoesNotExist:
|
||||||
raise HttpError(404, "User not found")
|
raise HttpError(404, "User not found")
|
||||||
|
elif payload.user_id and payload.user_id != request.user.id:
|
||||||
|
raise HttpError(403, "Forbidden")
|
||||||
name = (payload.name or "").strip()
|
name = (payload.name or "").strip()
|
||||||
if not name:
|
if not name:
|
||||||
raise HttpError(422, {"name": ["Name cannot be empty."]})
|
raise HttpError(422, {"name": ["Name cannot be empty."]})
|
||||||
@@ -110,25 +138,35 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/{key_id}", response=KeyOut)
|
@router.get("/{key_id}", response=KeyOut)
|
||||||
def get_key(request: HttpRequest, key_id: int):
|
def get_key(request: HttpRequest, key_id: int):
|
||||||
"""Get a specific SSH key if permitted."""
|
"""Get a specific SSH key by id.
|
||||||
_require_authenticated(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `keys.view_sshkey` on the object.
|
||||||
|
Rationale: used by key detail views and server access debugging.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
try:
|
try:
|
||||||
key = SSHKey.objects.get(id=key_id)
|
key = SSHKey.objects.get(id=key_id)
|
||||||
except SSHKey.DoesNotExist:
|
except SSHKey.DoesNotExist:
|
||||||
raise HttpError(404, "Not Found")
|
raise HttpError(404, "Not Found")
|
||||||
if not _is_admin(request) and key.user_id != request.user.id:
|
if not request.user.has_perm("keys.view_sshkey", key):
|
||||||
raise HttpError(403, "Forbidden")
|
raise HttpError(403, "Forbidden")
|
||||||
return _key_to_out(key)
|
return _key_to_out(key)
|
||||||
|
|
||||||
@router.patch("/{key_id}", response=KeyOut)
|
@router.patch("/{key_id}", response=KeyOut)
|
||||||
def update_key(request: HttpRequest, key_id: int, payload: KeyUpdateIn):
|
def update_key(request: HttpRequest, key_id: int, payload: KeyUpdateIn):
|
||||||
"""Update key name or active state if permitted."""
|
"""Update key name or active state.
|
||||||
_require_authenticated(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `keys.change_sshkey` on the object.
|
||||||
|
Rationale: allows key rotation and revocation without deletion.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
try:
|
try:
|
||||||
key = SSHKey.objects.get(id=key_id)
|
key = SSHKey.objects.get(id=key_id)
|
||||||
except SSHKey.DoesNotExist:
|
except SSHKey.DoesNotExist:
|
||||||
raise HttpError(404, "Not Found")
|
raise HttpError(404, "Not Found")
|
||||||
if not _is_admin(request) and key.user_id != request.user.id:
|
if not request.user.has_perm("keys.change_sshkey", key):
|
||||||
raise HttpError(403, "Forbidden")
|
raise HttpError(403, "Forbidden")
|
||||||
if payload.name is None and payload.is_active is None:
|
if payload.name is None and payload.is_active is None:
|
||||||
raise HttpError(422, {"detail": "No fields provided."})
|
raise HttpError(422, {"detail": "No fields provided."})
|
||||||
@@ -148,13 +186,19 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.delete("/{key_id}", response={204: None})
|
@router.delete("/{key_id}", response={204: None})
|
||||||
def delete_key(request: HttpRequest, key_id: int):
|
def delete_key(request: HttpRequest, key_id: int):
|
||||||
"""Revoke an SSH key if permitted (soft delete)."""
|
"""Revoke (soft delete) an SSH key.
|
||||||
_require_authenticated(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `keys.delete_sshkey` on the object.
|
||||||
|
Behavior: sets is_active false and revoked_at if key is active.
|
||||||
|
Rationale: removes key access while preserving auditability.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
try:
|
try:
|
||||||
key = SSHKey.objects.get(id=key_id)
|
key = SSHKey.objects.get(id=key_id)
|
||||||
except SSHKey.DoesNotExist:
|
except SSHKey.DoesNotExist:
|
||||||
raise HttpError(404, "Not Found")
|
raise HttpError(404, "Not Found")
|
||||||
if not _is_admin(request) and key.user_id != request.user.id:
|
if not request.user.has_perm("keys.delete_sshkey", key):
|
||||||
raise HttpError(403, "Forbidden")
|
raise HttpError(403, "Forbidden")
|
||||||
if key.is_active:
|
if key.is_active:
|
||||||
key.is_active = False
|
key.is_active = False
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
from django.db import IntegrityError
|
|
||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from ninja import File, Form, Router, Schema
|
from ninja import Router, Schema
|
||||||
from ninja.files import UploadedFile
|
|
||||||
from ninja.errors import HttpError
|
from ninja.errors import HttpError
|
||||||
|
from guardian.shortcuts import get_objects_for_user, get_perms
|
||||||
|
from apps.core.rbac import require_authenticated, require_perms
|
||||||
from apps.servers.models import Server
|
from apps.servers.models import Server
|
||||||
|
|
||||||
|
|
||||||
@@ -20,26 +20,8 @@ class ServerOut(Schema):
|
|||||||
initial: str
|
initial: str
|
||||||
|
|
||||||
|
|
||||||
class ServerCreate(Schema):
|
|
||||||
display_name: str
|
|
||||||
hostname: Optional[str] = None
|
|
||||||
ipv4: Optional[str] = None
|
|
||||||
ipv6: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class ServerUpdate(Schema):
|
class ServerUpdate(Schema):
|
||||||
display_name: Optional[str] = None
|
display_name: Optional[str] = None
|
||||||
hostname: Optional[str] = None
|
|
||||||
ipv4: Optional[str] = None
|
|
||||||
ipv6: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
def _require_admin(request: HttpRequest) -> None:
|
|
||||||
user = request.user
|
|
||||||
if not getattr(user, "is_authenticated", False):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
if not (user.is_staff or user.is_superuser):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
|
|
||||||
|
|
||||||
def build_router() -> Router:
|
def build_router() -> Router:
|
||||||
@@ -47,8 +29,20 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/", response=List[ServerOut])
|
@router.get("/", response=List[ServerOut])
|
||||||
def list_servers(request: HttpRequest):
|
def list_servers(request: HttpRequest):
|
||||||
"""List servers visible to authenticated users."""
|
"""List servers the caller can view.
|
||||||
servers = Server.objects.all()
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `servers.view_server` via object permissions.
|
||||||
|
Behavior: returns only servers the user can see via object perms.
|
||||||
|
Rationale: drives the server dashboard and access-aware navigation.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
|
servers = get_objects_for_user(
|
||||||
|
request.user,
|
||||||
|
"servers.view_server",
|
||||||
|
klass=Server,
|
||||||
|
accept_global_perms=False,
|
||||||
|
)
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
"id": s.id,
|
"id": s.id,
|
||||||
@@ -64,61 +58,20 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/{server_id}", response=ServerOut)
|
@router.get("/{server_id}", response=ServerOut)
|
||||||
def get_server(request: HttpRequest, server_id: int):
|
def get_server(request: HttpRequest, server_id: int):
|
||||||
"""Get server details by id."""
|
"""Get a server record by id.
|
||||||
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `servers.view_server` via object permissions.
|
||||||
|
Rationale: used by server detail views and API clients inspecting
|
||||||
|
server metadata (hostname/IPs populated by the agent).
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
try:
|
try:
|
||||||
server = Server.objects.get(id=server_id)
|
server = Server.objects.get(id=server_id)
|
||||||
except Server.DoesNotExist:
|
except Server.DoesNotExist:
|
||||||
raise HttpError(404, "Not Found")
|
raise HttpError(404, "Not Found")
|
||||||
return {
|
if "view_server" not in get_perms(request.user, server):
|
||||||
"id": server.id,
|
raise HttpError(403, "Forbidden")
|
||||||
"display_name": server.display_name,
|
|
||||||
"hostname": server.hostname,
|
|
||||||
"ipv4": server.ipv4,
|
|
||||||
"ipv6": server.ipv6,
|
|
||||||
"image_url": server.image_url,
|
|
||||||
"initial": server.initial,
|
|
||||||
}
|
|
||||||
|
|
||||||
@router.post("/", response=ServerOut)
|
|
||||||
def create_server_json(request: HttpRequest, payload: ServerCreate):
|
|
||||||
"""Create a server using JSON payload (admin only)."""
|
|
||||||
_require_admin(request)
|
|
||||||
server = Server.objects.create(
|
|
||||||
display_name=payload.display_name.strip(),
|
|
||||||
hostname=(payload.hostname or "").strip() or None,
|
|
||||||
ipv4=(payload.ipv4 or "").strip() or None,
|
|
||||||
ipv6=(payload.ipv6 or "").strip() or None,
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
"id": server.id,
|
|
||||||
"display_name": server.display_name,
|
|
||||||
"hostname": server.hostname,
|
|
||||||
"ipv4": server.ipv4,
|
|
||||||
"ipv6": server.ipv6,
|
|
||||||
"image_url": server.image_url,
|
|
||||||
"initial": server.initial,
|
|
||||||
}
|
|
||||||
|
|
||||||
@router.post("/upload", response=ServerOut)
|
|
||||||
def create_server_multipart(
|
|
||||||
request: HttpRequest,
|
|
||||||
display_name: str = Form(...),
|
|
||||||
hostname: Optional[str] = Form(None),
|
|
||||||
ipv4: Optional[str] = Form(None),
|
|
||||||
ipv6: Optional[str] = Form(None),
|
|
||||||
image: Optional[UploadedFile] = File(None),
|
|
||||||
):
|
|
||||||
"""Create a server with optional image upload (admin only)."""
|
|
||||||
_require_admin(request)
|
|
||||||
server = Server(
|
|
||||||
display_name=display_name.strip(),
|
|
||||||
hostname=(hostname or "").strip() or None,
|
|
||||||
ipv4=(ipv4 or "").strip() or None,
|
|
||||||
ipv6=(ipv6 or "").strip() or None,
|
|
||||||
)
|
|
||||||
if image:
|
|
||||||
server.image.save(image.name, image) # type: ignore[arg-type]
|
|
||||||
server.save()
|
|
||||||
return {
|
return {
|
||||||
"id": server.id,
|
"id": server.id,
|
||||||
"display_name": server.display_name,
|
"display_name": server.display_name,
|
||||||
@@ -131,34 +84,26 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.patch("/{server_id}", response=ServerOut)
|
@router.patch("/{server_id}", response=ServerOut)
|
||||||
def update_server(request: HttpRequest, server_id: int, payload: ServerUpdate):
|
def update_server(request: HttpRequest, server_id: int, payload: ServerUpdate):
|
||||||
"""Update server fields (admin only)."""
|
"""Update the server display name (admin only).
|
||||||
_require_admin(request)
|
|
||||||
if (
|
Auth: required.
|
||||||
payload.display_name is None
|
Permissions: requires `servers.change_server`.
|
||||||
and payload.hostname is None
|
Behavior: only display_name is editable via API; host/IP data is owned
|
||||||
and payload.ipv4 is None
|
by the agent heartbeat to avoid conflicting sources of truth.
|
||||||
and payload.ipv6 is None
|
Rationale: allows human-friendly naming without bypassing enrollment.
|
||||||
):
|
"""
|
||||||
|
require_perms(request, "servers.change_server")
|
||||||
|
if payload.display_name is None:
|
||||||
raise HttpError(422, {"detail": "No fields provided."})
|
raise HttpError(422, {"detail": "No fields provided."})
|
||||||
try:
|
try:
|
||||||
server = Server.objects.get(id=server_id)
|
server = Server.objects.get(id=server_id)
|
||||||
except Server.DoesNotExist:
|
except Server.DoesNotExist:
|
||||||
raise HttpError(404, "Not Found")
|
raise HttpError(404, "Not Found")
|
||||||
if payload.display_name is not None:
|
|
||||||
display_name = payload.display_name.strip()
|
display_name = payload.display_name.strip()
|
||||||
if not display_name:
|
if not display_name:
|
||||||
raise HttpError(422, {"display_name": ["Display name cannot be empty."]})
|
raise HttpError(422, {"display_name": ["Display name cannot be empty."]})
|
||||||
server.display_name = display_name
|
server.display_name = display_name
|
||||||
if payload.hostname is not None:
|
server.save(update_fields=["display_name"])
|
||||||
server.hostname = (payload.hostname or "").strip() or None
|
|
||||||
if payload.ipv4 is not None:
|
|
||||||
server.ipv4 = (payload.ipv4 or "").strip() or None
|
|
||||||
if payload.ipv6 is not None:
|
|
||||||
server.ipv6 = (payload.ipv6 or "").strip() or None
|
|
||||||
try:
|
|
||||||
server.save()
|
|
||||||
except IntegrityError:
|
|
||||||
raise HttpError(422, {"detail": "Unique constraint violated."})
|
|
||||||
return {
|
return {
|
||||||
"id": server.id,
|
"id": server.id,
|
||||||
"display_name": server.display_name,
|
"display_name": server.display_name,
|
||||||
@@ -169,17 +114,6 @@ def build_router() -> Router:
|
|||||||
"initial": server.initial,
|
"initial": server.initial,
|
||||||
}
|
}
|
||||||
|
|
||||||
@router.delete("/{server_id}", response={204: None})
|
|
||||||
def delete_server(request: HttpRequest, server_id: int):
|
|
||||||
"""Delete a server by id (admin only)."""
|
|
||||||
_require_admin(request)
|
|
||||||
try:
|
|
||||||
server = Server.objects.get(id=server_id)
|
|
||||||
except Server.DoesNotExist:
|
|
||||||
raise HttpError(404, "Not Found")
|
|
||||||
server.delete()
|
|
||||||
return 204, None
|
|
||||||
|
|
||||||
return router
|
return router
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ from typing import Literal, TypedDict
|
|||||||
|
|
||||||
from ninja import Router
|
from ninja import Router
|
||||||
|
|
||||||
|
from apps.core.rbac import require_authenticated
|
||||||
|
|
||||||
|
|
||||||
class HealthResponse(TypedDict):
|
class HealthResponse(TypedDict):
|
||||||
status: Literal["ok"]
|
status: Literal["ok"]
|
||||||
@@ -11,8 +13,16 @@ def build_router() -> Router:
|
|||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
@router.get("/health", response=HealthResponse)
|
@router.get("/health", response=HealthResponse)
|
||||||
def health() -> HealthResponse:
|
def health(request) -> HealthResponse:
|
||||||
"""Health check endpoint for service monitoring."""
|
"""Return application liveness for internal monitoring.
|
||||||
|
|
||||||
|
Auth: required (session or JWT). This is intentionally protected to avoid
|
||||||
|
exposing internal status to unauthenticated callers.
|
||||||
|
Behavior: returns a static {"status": "ok"} if the app stack is reachable.
|
||||||
|
Rationale: used by uptime checks and deployments to confirm the API
|
||||||
|
process is running and can authenticate requests.
|
||||||
|
"""
|
||||||
|
require_authenticated(request)
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
return router
|
return router
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from ninja import Query, Router, Schema
|
|||||||
from ninja.errors import HttpError
|
from ninja.errors import HttpError
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
|
||||||
|
from apps.core.rbac import require_perms
|
||||||
from apps.servers.models import Server
|
from apps.servers.models import Server
|
||||||
from apps.telemetry.models import TelemetryEvent
|
from apps.telemetry.models import TelemetryEvent
|
||||||
|
|
||||||
@@ -51,14 +52,6 @@ class TelemetryQuery(Schema):
|
|||||||
success: Optional[bool] = None
|
success: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
def _require_admin(request: HttpRequest) -> None:
|
|
||||||
user = request.user
|
|
||||||
if not getattr(user, "is_authenticated", False):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
if not (user.is_staff or user.is_superuser):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
|
|
||||||
|
|
||||||
def _event_to_out(event: TelemetryEvent) -> TelemetryOut:
|
def _event_to_out(event: TelemetryEvent) -> TelemetryOut:
|
||||||
return TelemetryOut(
|
return TelemetryOut(
|
||||||
id=event.id,
|
id=event.id,
|
||||||
@@ -78,8 +71,14 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/", response=List[TelemetryOut])
|
@router.get("/", response=List[TelemetryOut])
|
||||||
def list_events(request: HttpRequest, filters: TelemetryQuery = Query(...)):
|
def list_events(request: HttpRequest, filters: TelemetryQuery = Query(...)):
|
||||||
"""List telemetry events with filters (admin only)."""
|
"""List telemetry events emitted by the platform and agents.
|
||||||
_require_admin(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `telemetry.view_telemetryevent`.
|
||||||
|
Filters: event_type, server_id, user_id, success.
|
||||||
|
Rationale: supports operational dashboards and audit-style timelines.
|
||||||
|
"""
|
||||||
|
require_perms(request, "telemetry.view_telemetryevent")
|
||||||
qs = TelemetryEvent.objects.order_by("-created_at")
|
qs = TelemetryEvent.objects.order_by("-created_at")
|
||||||
if filters.event_type:
|
if filters.event_type:
|
||||||
qs = qs.filter(event_type=filters.event_type)
|
qs = qs.filter(event_type=filters.event_type)
|
||||||
@@ -94,8 +93,15 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.post("/", response=TelemetryOut)
|
@router.post("/", response=TelemetryOut)
|
||||||
def create_event(request: HttpRequest, payload: TelemetryCreateIn):
|
def create_event(request: HttpRequest, payload: TelemetryCreateIn):
|
||||||
"""Create a telemetry event entry (admin only)."""
|
"""Create a telemetry event entry.
|
||||||
_require_admin(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `telemetry.add_telemetryevent`.
|
||||||
|
Behavior: validates server/user references and normalizes source.
|
||||||
|
Rationale: used by internal automation; if external clients are not
|
||||||
|
expected to emit telemetry, this endpoint can be restricted further.
|
||||||
|
"""
|
||||||
|
require_perms(request, "telemetry.add_telemetryevent")
|
||||||
server = None
|
server = None
|
||||||
if payload.server_id:
|
if payload.server_id:
|
||||||
try:
|
try:
|
||||||
@@ -122,8 +128,13 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/summary", response=TelemetrySummaryOut)
|
@router.get("/summary", response=TelemetrySummaryOut)
|
||||||
def summary(request: HttpRequest):
|
def summary(request: HttpRequest):
|
||||||
"""Return a high-level telemetry summary (admin only)."""
|
"""Return a high-level success/failure summary.
|
||||||
_require_admin(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `telemetry.view_telemetryevent`.
|
||||||
|
Rationale: feeds dashboard widgets without pulling full event lists.
|
||||||
|
"""
|
||||||
|
require_perms(request, "telemetry.view_telemetryevent")
|
||||||
totals = TelemetryEvent.objects.aggregate(
|
totals = TelemetryEvent.objects.aggregate(
|
||||||
total=Count("id"),
|
total=Count("id"),
|
||||||
success=Count("id", filter=models.Q(success=True)),
|
success=Count("id", filter=models.Q(success=True)),
|
||||||
|
|||||||
@@ -9,11 +9,13 @@ from ninja import Query, Router, Schema
|
|||||||
from ninja.errors import HttpError
|
from ninja.errors import HttpError
|
||||||
from pydantic import EmailStr, Field
|
from pydantic import EmailStr, Field
|
||||||
|
|
||||||
|
from apps.core.rbac import ROLE_USER, get_user_role, require_perms, set_user_role
|
||||||
|
|
||||||
|
|
||||||
class UserCreateIn(Schema):
|
class UserCreateIn(Schema):
|
||||||
email: EmailStr
|
email: EmailStr
|
||||||
password: str = Field(min_length=8)
|
password: str = Field(min_length=8)
|
||||||
role: Literal["admin", "user"]
|
role: Literal["administrator", "operator", "auditor", "user", "admin"]
|
||||||
|
|
||||||
|
|
||||||
class UserListOut(Schema):
|
class UserListOut(Schema):
|
||||||
@@ -33,7 +35,7 @@ class UserDetailOut(Schema):
|
|||||||
class UserUpdateIn(Schema):
|
class UserUpdateIn(Schema):
|
||||||
email: EmailStr | None = None
|
email: EmailStr | None = None
|
||||||
password: str | None = Field(default=None, min_length=8)
|
password: str | None = Field(default=None, min_length=8)
|
||||||
role: Literal["admin", "user"] | None = None
|
role: Literal["administrator", "operator", "auditor", "user", "admin"] | None = None
|
||||||
is_active: bool | None = None
|
is_active: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
@@ -42,25 +44,8 @@ class UsersQuery(Schema):
|
|||||||
offset: int = Field(default=0, ge=0)
|
offset: int = Field(default=0, ge=0)
|
||||||
|
|
||||||
|
|
||||||
def _require_admin(request: HttpRequest) -> None:
|
|
||||||
user = request.user
|
|
||||||
if not getattr(user, "is_authenticated", False):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
if not (user.is_staff or user.is_superuser):
|
|
||||||
raise HttpError(403, "Forbidden")
|
|
||||||
|
|
||||||
|
|
||||||
def _role_from_user(user) -> str:
|
def _role_from_user(user) -> str:
|
||||||
return "admin" if (user.is_staff or user.is_superuser) else "user"
|
return get_user_role(user) or ROLE_USER
|
||||||
|
|
||||||
|
|
||||||
def _apply_role(user, role: str) -> None:
|
|
||||||
if role == "admin":
|
|
||||||
user.is_staff = True
|
|
||||||
user.is_superuser = True
|
|
||||||
else:
|
|
||||||
user.is_staff = False
|
|
||||||
user.is_superuser = False
|
|
||||||
|
|
||||||
|
|
||||||
def build_router() -> Router:
|
def build_router() -> Router:
|
||||||
@@ -68,19 +53,31 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.post("/", response=UserDetailOut)
|
@router.post("/", response=UserDetailOut)
|
||||||
def create_user(request: HttpRequest, payload: UserCreateIn):
|
def create_user(request: HttpRequest, payload: UserCreateIn):
|
||||||
"""Create a user with role and password (admin only)."""
|
"""Create a platform user and assign a Keywarden role.
|
||||||
_require_admin(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `auth.add_user` (admin/operator).
|
||||||
|
Behavior: uses email as username, hashes the password, and assigns a
|
||||||
|
role which maps to Keywarden group permissions.
|
||||||
|
Rationale: enables automation and external admin workflows; mirrors
|
||||||
|
the admin UI user creation flow.
|
||||||
|
"""
|
||||||
|
require_perms(request, "auth.add_user")
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
email = payload.email.strip().lower()
|
email = payload.email.strip().lower()
|
||||||
if User.objects.filter(email__iexact=email).exists():
|
if User.objects.filter(email__iexact=email).exists():
|
||||||
raise HttpError(422, {"email": ["Email already exists."]})
|
raise HttpError(422, {"email": ["Email already exists."]})
|
||||||
user = User(username=email, email=email, is_active=True)
|
user = User(username=email, email=email, is_active=True)
|
||||||
_apply_role(user, payload.role)
|
|
||||||
user.set_password(payload.password)
|
user.set_password(payload.password)
|
||||||
try:
|
try:
|
||||||
user.save()
|
user.save()
|
||||||
except IntegrityError:
|
except IntegrityError:
|
||||||
raise HttpError(422, {"email": ["Email already exists."]})
|
raise HttpError(422, {"email": ["Email already exists."]})
|
||||||
|
try:
|
||||||
|
set_user_role(user, payload.role)
|
||||||
|
except ValueError:
|
||||||
|
raise HttpError(422, {"role": ["Invalid role."]})
|
||||||
|
user.save()
|
||||||
return {
|
return {
|
||||||
"id": user.id,
|
"id": user.id,
|
||||||
"email": user.email,
|
"email": user.email,
|
||||||
@@ -90,8 +87,14 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/", response=List[UserListOut])
|
@router.get("/", response=List[UserListOut])
|
||||||
def list_users(request: HttpRequest, pagination: UsersQuery = Query(...)):
|
def list_users(request: HttpRequest, pagination: UsersQuery = Query(...)):
|
||||||
"""List users with pagination (admin only)."""
|
"""List users for administrative visibility and access management.
|
||||||
_require_admin(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `auth.view_user`.
|
||||||
|
Pagination: limit + offset.
|
||||||
|
Rationale: used by admin UI and automation to audit user access.
|
||||||
|
"""
|
||||||
|
require_perms(request, "auth.view_user")
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
qs = User.objects.order_by("id")[pagination.offset : pagination.offset + pagination.limit]
|
qs = User.objects.order_by("id")[pagination.offset : pagination.offset + pagination.limit]
|
||||||
return [
|
return [
|
||||||
@@ -106,8 +109,13 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.get("/{user_id}", response=UserDetailOut)
|
@router.get("/{user_id}", response=UserDetailOut)
|
||||||
def get_user(request: HttpRequest, user_id: int):
|
def get_user(request: HttpRequest, user_id: int):
|
||||||
"""Get user details by id (admin only)."""
|
"""Fetch a single user record for inspection.
|
||||||
_require_admin(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `auth.view_user`.
|
||||||
|
Rationale: used by admin detail views and automation scripts.
|
||||||
|
"""
|
||||||
|
require_perms(request, "auth.view_user")
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
try:
|
try:
|
||||||
user = User.objects.get(id=user_id)
|
user = User.objects.get(id=user_id)
|
||||||
@@ -122,8 +130,14 @@ def build_router() -> Router:
|
|||||||
|
|
||||||
@router.patch("/{user_id}", response=UserDetailOut)
|
@router.patch("/{user_id}", response=UserDetailOut)
|
||||||
def update_user(request: HttpRequest, user_id: int, payload: UserUpdateIn):
|
def update_user(request: HttpRequest, user_id: int, payload: UserUpdateIn):
|
||||||
"""Update user fields such as role, email, or status (admin only)."""
|
"""Update user identity, role, password, or activation state.
|
||||||
_require_admin(request)
|
|
||||||
|
Auth: required.
|
||||||
|
Permissions: requires `auth.change_user` (admin).
|
||||||
|
Side effects: role changes update Keywarden role/group mappings.
|
||||||
|
Rationale: required for role delegation and account lifecycle control.
|
||||||
|
"""
|
||||||
|
require_perms(request, "auth.change_user")
|
||||||
if payload.email is None and payload.password is None and payload.role is None and payload.is_active is None:
|
if payload.email is None and payload.password is None and payload.role is None and payload.is_active is None:
|
||||||
raise HttpError(422, {"detail": "No fields provided."})
|
raise HttpError(422, {"detail": "No fields provided."})
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
@@ -140,7 +154,10 @@ def build_router() -> Router:
|
|||||||
if payload.password is not None:
|
if payload.password is not None:
|
||||||
user.set_password(payload.password)
|
user.set_password(payload.password)
|
||||||
if payload.role is not None:
|
if payload.role is not None:
|
||||||
_apply_role(user, payload.role)
|
try:
|
||||||
|
set_user_role(user, payload.role)
|
||||||
|
except ValueError:
|
||||||
|
raise HttpError(422, {"role": ["Invalid role."]})
|
||||||
if payload.is_active is not None:
|
if payload.is_active is not None:
|
||||||
user.is_active = payload.is_active
|
user.is_active = payload.is_active
|
||||||
user.save()
|
user.save()
|
||||||
@@ -151,18 +168,6 @@ def build_router() -> Router:
|
|||||||
"is_active": user.is_active,
|
"is_active": user.is_active,
|
||||||
}
|
}
|
||||||
|
|
||||||
@router.delete("/{user_id}", response={204: None})
|
|
||||||
def delete_user(request: HttpRequest, user_id: int):
|
|
||||||
"""Delete a user by id (admin only)."""
|
|
||||||
_require_admin(request)
|
|
||||||
User = get_user_model()
|
|
||||||
try:
|
|
||||||
user = User.objects.get(id=user_id)
|
|
||||||
except User.DoesNotExist:
|
|
||||||
raise HttpError(404, "Not Found")
|
|
||||||
user.delete()
|
|
||||||
return 204, None
|
|
||||||
|
|
||||||
return router
|
return router
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
9
app/keywarden/celery.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
from celery import Celery
|
||||||
|
|
||||||
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "keywarden.settings.dev")
|
||||||
|
|
||||||
|
app = Celery("keywarden")
|
||||||
|
app.config_from_object("django.conf:settings", namespace="CELERY")
|
||||||
|
app.autodiscover_tasks()
|
||||||
@@ -3,6 +3,7 @@ from pathlib import Path
|
|||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
from django.urls import reverse_lazy
|
from django.urls import reverse_lazy
|
||||||
|
from django.templatetags.static import static
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
@@ -24,6 +25,7 @@ CSRF_COOKIE_SECURE = True
|
|||||||
SESSION_COOKIE_SECURE = True
|
SESSION_COOKIE_SECURE = True
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
|
"unfold.contrib.guardian",
|
||||||
"unfold", # Admin UI
|
"unfold", # Admin UI
|
||||||
"unfold.contrib.filters",
|
"unfold.contrib.filters",
|
||||||
"django.contrib.admin",
|
"django.contrib.admin",
|
||||||
@@ -32,19 +34,21 @@ INSTALLED_APPS = [
|
|||||||
"django.contrib.sessions",
|
"django.contrib.sessions",
|
||||||
"django.contrib.messages",
|
"django.contrib.messages",
|
||||||
"django.contrib.staticfiles",
|
"django.contrib.staticfiles",
|
||||||
|
"guardian",
|
||||||
"rest_framework",
|
"rest_framework",
|
||||||
"apps.audit",
|
"apps.audit",
|
||||||
"apps.accounts",
|
"apps.accounts",
|
||||||
"apps.core",
|
"apps.core.apps.CoreConfig",
|
||||||
"apps.dashboard",
|
"apps.dashboard",
|
||||||
"apps.servers",
|
"apps.servers.apps.ServersConfig",
|
||||||
"apps.keys",
|
"apps.keys.apps.KeysConfig",
|
||||||
"apps.access",
|
"apps.access.apps.AccessConfig",
|
||||||
"apps.telemetry",
|
"apps.telemetry",
|
||||||
"ninja", # Django Ninja API
|
"ninja", # Django Ninja API
|
||||||
"mozilla_django_oidc", # OIDC Client
|
"mozilla_django_oidc", # OIDC Client
|
||||||
"tailwind",
|
"tailwind",
|
||||||
"theme"
|
"theme",
|
||||||
|
"keywarden"
|
||||||
]
|
]
|
||||||
|
|
||||||
MIDDLEWARE = [
|
MIDDLEWARE = [
|
||||||
@@ -54,6 +58,7 @@ MIDDLEWARE = [
|
|||||||
"django.middleware.common.CommonMiddleware",
|
"django.middleware.common.CommonMiddleware",
|
||||||
"django.middleware.csrf.CsrfViewMiddleware",
|
"django.middleware.csrf.CsrfViewMiddleware",
|
||||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||||
|
"apps.audit.middleware.ApiAuditLogMiddleware",
|
||||||
"django.contrib.messages.middleware.MessageMiddleware",
|
"django.contrib.messages.middleware.MessageMiddleware",
|
||||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||||
]
|
]
|
||||||
@@ -78,10 +83,12 @@ DATABASES = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
REDIS_URL = os.getenv("KEYWARDEN_REDIS_URL", "redis://127.0.0.1:6379/1")
|
||||||
|
|
||||||
CACHES = {
|
CACHES = {
|
||||||
"default": {
|
"default": {
|
||||||
"BACKEND": "django_redis.cache.RedisCache",
|
"BACKEND": "django_redis.cache.RedisCache",
|
||||||
"LOCATION": "redis://keywarden-valkey:6379/1",
|
"LOCATION": REDIS_URL,
|
||||||
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},
|
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -89,6 +96,21 @@ CACHES = {
|
|||||||
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
|
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
|
||||||
SESSION_CACHE_ALIAS = "default"
|
SESSION_CACHE_ALIAS = "default"
|
||||||
|
|
||||||
|
KEYWARDEN_AGENT_CERT_VALIDITY_DAYS = int(os.getenv("KEYWARDEN_AGENT_CERT_VALIDITY_DAYS", "90"))
|
||||||
|
|
||||||
|
CELERY_BROKER_URL = os.getenv("KEYWARDEN_CELERY_BROKER_URL", REDIS_URL)
|
||||||
|
CELERY_RESULT_BACKEND = os.getenv("KEYWARDEN_CELERY_RESULT_BACKEND", REDIS_URL)
|
||||||
|
CELERY_ACCEPT_CONTENT = ["json"]
|
||||||
|
CELERY_TASK_SERIALIZER = "json"
|
||||||
|
CELERY_RESULT_SERIALIZER = "json"
|
||||||
|
CELERY_TIMEZONE = "UTC"
|
||||||
|
CELERY_BEAT_SCHEDULE = {
|
||||||
|
"expire-access-requests": {
|
||||||
|
"task": "apps.access.tasks.expire_access_requests",
|
||||||
|
"schedule": 60.0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
PASSWORD_HASHERS = [
|
PASSWORD_HASHERS = [
|
||||||
"django.contrib.auth.hashers.Argon2PasswordHasher",
|
"django.contrib.auth.hashers.Argon2PasswordHasher",
|
||||||
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
|
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
|
||||||
@@ -121,8 +143,25 @@ TEMPLATES = [
|
|||||||
# AUTHENTICATION_BACKENDS is configured dynamically below based on KEYWARDEN_AUTH_MODE
|
# AUTHENTICATION_BACKENDS is configured dynamically below based on KEYWARDEN_AUTH_MODE
|
||||||
|
|
||||||
UNFOLD = {
|
UNFOLD = {
|
||||||
"SITE_TITLE": "Keywarden Admin",
|
"SITE_ICON": lambda request: static("branding/keywarden-favicon.svg"),
|
||||||
|
"SITE_LOGO": lambda request: static("branding/keywarden-favicon.svg"),
|
||||||
|
"SITE_TITLE": "Admin - Keywarden",
|
||||||
"SITE_HEADER": "Keywarden",
|
"SITE_HEADER": "Keywarden",
|
||||||
|
"SITE_FAVICONS": [
|
||||||
|
{
|
||||||
|
"rel": "icon",
|
||||||
|
"sizes": "32x32",
|
||||||
|
"type": "image/svg+xml",
|
||||||
|
"href": lambda request: static("branding/keywarden-favicon.svg"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"SITE_DROPDOWN": [
|
||||||
|
{
|
||||||
|
"icon": "diamond",
|
||||||
|
"title": _("Gitea"),
|
||||||
|
"link": "https://git.ntbx.io/boris/keywarden",
|
||||||
|
},
|
||||||
|
],
|
||||||
"SHOW_HISTORY": True,
|
"SHOW_HISTORY": True,
|
||||||
"SITE_URL": "/",
|
"SITE_URL": "/",
|
||||||
"LOGIN_REDIRECT_URL": "/admin/",
|
"LOGIN_REDIRECT_URL": "/admin/",
|
||||||
@@ -150,42 +189,39 @@ UNFOLD = {
|
|||||||
"STYLES": [
|
"STYLES": [
|
||||||
"/static/unfold/css/styles.css",
|
"/static/unfold/css/styles.css",
|
||||||
"/static/unfold/css/simplebar.css",
|
"/static/unfold/css/simplebar.css",
|
||||||
(lambda request: "/static/unfold/css/keywarden.css"),
|
#(lambda request: "/static/unfold/css/keywarden.css"),
|
||||||
],
|
|
||||||
"SCRIPTS": [
|
|
||||||
"/static/unfold/js/simplebar.js",
|
|
||||||
],
|
|
||||||
"TABS": [
|
|
||||||
{
|
|
||||||
"models": [
|
|
||||||
"auth.User",
|
|
||||||
],
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"title": _("Logs"),
|
|
||||||
"link": reverse_lazy("admin:audit_auditlog_changelist"),
|
|
||||||
"attrs": {"hx-boost": "true"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"title": _("Event Types"),
|
|
||||||
"link": reverse_lazy("admin:audit_auditeventtype_changelist"),
|
|
||||||
"attrs": {"hx-boost": "true"},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"models": [
|
|
||||||
"servers.Server",
|
|
||||||
],
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"title": _("Servers"),
|
|
||||||
"link": reverse_lazy("admin:servers_server_changelist"),
|
|
||||||
"attrs": {"hx-boost": "true"},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
|
# "TABS": [
|
||||||
|
# {
|
||||||
|
# "models": [
|
||||||
|
# "auth.User",
|
||||||
|
# ],
|
||||||
|
# "items": [
|
||||||
|
# {
|
||||||
|
# "title": _("Logs"),
|
||||||
|
# "link": reverse_lazy("admin:audit_auditlog_changelist"),
|
||||||
|
# "attrs": {"hx-boost": "true"},
|
||||||
|
# },
|
||||||
|
# {
|
||||||
|
# "title": _("Event Types"),
|
||||||
|
# "link": reverse_lazy("admin:audit_auditeventtype_changelist"),
|
||||||
|
# "attrs": {"hx-boost": "true"},
|
||||||
|
# },
|
||||||
|
# ],
|
||||||
|
# },
|
||||||
|
# {
|
||||||
|
# "models": [
|
||||||
|
# "servers.Server",
|
||||||
|
# ],
|
||||||
|
# "items": [
|
||||||
|
# {
|
||||||
|
# "title": _("Servers"),
|
||||||
|
# "link": reverse_lazy("admin:servers_server_changelist"),
|
||||||
|
# "attrs": {"hx-boost": "true"},
|
||||||
|
# },
|
||||||
|
# ],
|
||||||
|
# },
|
||||||
|
# ],
|
||||||
}
|
}
|
||||||
MEDIA_URL = "/media/"
|
MEDIA_URL = "/media/"
|
||||||
MEDIA_ROOT = BASE_DIR/"media"
|
MEDIA_ROOT = BASE_DIR/"media"
|
||||||
@@ -205,6 +241,8 @@ KEYWARDEN_AUTH_MODE = AUTH_MODE
|
|||||||
|
|
||||||
if AUTH_MODE == "oidc":
|
if AUTH_MODE == "oidc":
|
||||||
AUTHENTICATION_BACKENDS = [
|
AUTHENTICATION_BACKENDS = [
|
||||||
|
"django.contrib.auth.backends.ModelBackend",
|
||||||
|
"guardian.backends.ObjectPermissionBackend",
|
||||||
"mozilla_django_oidc.auth.OIDCAuthenticationBackend",
|
"mozilla_django_oidc.auth.OIDCAuthenticationBackend",
|
||||||
]
|
]
|
||||||
LOGIN_URL = "/oidc/authenticate/"
|
LOGIN_URL = "/oidc/authenticate/"
|
||||||
@@ -212,12 +250,15 @@ else:
|
|||||||
# native or hybrid -> allow both, native first for precedence
|
# native or hybrid -> allow both, native first for precedence
|
||||||
AUTHENTICATION_BACKENDS = [
|
AUTHENTICATION_BACKENDS = [
|
||||||
"django.contrib.auth.backends.ModelBackend",
|
"django.contrib.auth.backends.ModelBackend",
|
||||||
|
"guardian.backends.ObjectPermissionBackend",
|
||||||
"mozilla_django_oidc.auth.OIDCAuthenticationBackend",
|
"mozilla_django_oidc.auth.OIDCAuthenticationBackend",
|
||||||
]
|
]
|
||||||
LOGIN_URL = "/accounts/login/"
|
LOGIN_URL = "/accounts/login/"
|
||||||
LOGOUT_URL = "/oidc/logout/"
|
LOGOUT_URL = "/oidc/logout/"
|
||||||
LOGIN_REDIRECT_URL = "/"
|
LOGIN_REDIRECT_URL = "/servers/"
|
||||||
LOGOUT_REDIRECT_URL = "/"
|
LOGOUT_REDIRECT_URL = "/"
|
||||||
|
|
||||||
|
ANONYMOUS_USER_NAME = None
|
||||||
|
|
||||||
def permission_callback(request):
|
def permission_callback(request):
|
||||||
return request.user.has_perm("keywarden.change_model")
|
return request.user.has_perm("keywarden.change_model")
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ urlpatterns = [
|
|||||||
path("admin/", admin.site.urls),
|
path("admin/", admin.site.urls),
|
||||||
path("oidc/", include("mozilla_django_oidc.urls")),
|
path("oidc/", include("mozilla_django_oidc.urls")),
|
||||||
path("accounts/", include("apps.accounts.urls")),
|
path("accounts/", include("apps.accounts.urls")),
|
||||||
|
path("servers/", include("apps.servers.urls")),
|
||||||
# API
|
# API
|
||||||
path("api/", ninja_api.urls),
|
path("api/", ninja_api.urls),
|
||||||
path("api/v1/", ninja_api_v1.urls),
|
path("api/v1/", ninja_api_v1.urls),
|
||||||
path("api/auth/jwt/create/", TokenObtainPairView.as_view(), name="jwt-create"),
|
path("api/auth/jwt/create/", TokenObtainPairView.as_view(), name="jwt-create"),
|
||||||
path("api/auth/jwt/refresh/", TokenRefreshView.as_view(), name="jwt-refresh"),
|
path("api/auth/jwt/refresh/", TokenRefreshView.as_view(), name="jwt-refresh"),
|
||||||
path("", RedirectView.as_view(pattern_name="accounts:login", permanent=False)),
|
path("", RedirectView.as_view(pattern_name="servers:dashboard", permanent=False)),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -34,9 +34,16 @@ html[data-theme="light"],
|
|||||||
|
|
||||||
--error-fg: #ba2121;
|
--error-fg: #ba2121;
|
||||||
|
|
||||||
|
--message-debug-bg: #efefef;
|
||||||
|
--message-debug-icon: url(../img/icon-debug.svg);
|
||||||
|
--message-info-bg: #ccefff;
|
||||||
|
--message-info-icon: url(../img/icon-info.svg);
|
||||||
--message-success-bg: #dfd;
|
--message-success-bg: #dfd;
|
||||||
|
--message-success-icon: url(../img/icon-yes.svg);
|
||||||
--message-warning-bg: #ffc;
|
--message-warning-bg: #ffc;
|
||||||
|
--message-warning-icon: url(../img/icon-alert.svg);
|
||||||
--message-error-bg: #ffefef;
|
--message-error-bg: #ffefef;
|
||||||
|
--message-error-icon: url(../img/icon-no.svg);
|
||||||
|
|
||||||
--darkened-bg: #f8f8f8; /* A bit darker than --body-bg */
|
--darkened-bg: #f8f8f8; /* A bit darker than --body-bg */
|
||||||
--selected-bg: #e4e4e4; /* E.g. selected table cells */
|
--selected-bg: #e4e4e4; /* E.g. selected table cells */
|
||||||
@@ -118,6 +125,16 @@ a:focus {
|
|||||||
text-decoration: underline;
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
a:not(
|
||||||
|
[role="button"],
|
||||||
|
#header a,
|
||||||
|
#nav-sidebar a,
|
||||||
|
#content-main.app-list a,
|
||||||
|
.object-tools a
|
||||||
|
) {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
a img {
|
a img {
|
||||||
border: none;
|
border: none;
|
||||||
}
|
}
|
||||||
@@ -226,10 +243,10 @@ details summary {
|
|||||||
|
|
||||||
blockquote {
|
blockquote {
|
||||||
font-size: 0.6875rem;
|
font-size: 0.6875rem;
|
||||||
color: #777;
|
color: var(--body-quiet-color);
|
||||||
margin-left: 2px;
|
margin-left: 2px;
|
||||||
padding-left: 10px;
|
padding-left: 10px;
|
||||||
border-left: 5px solid #ddd;
|
border-left: 5px solid currentColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
code, pre {
|
code, pre {
|
||||||
@@ -628,20 +645,44 @@ ul.messagelist li {
|
|||||||
font-size: 0.8125rem;
|
font-size: 0.8125rem;
|
||||||
padding: 10px 10px 10px 65px;
|
padding: 10px 10px 10px 65px;
|
||||||
margin: 0 0 10px 0;
|
margin: 0 0 10px 0;
|
||||||
background: var(--message-success-bg) url(../img/icon-yes.svg) 40px 12px no-repeat;
|
|
||||||
background-size: 16px auto;
|
|
||||||
color: var(--body-fg);
|
color: var(--body-fg);
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
|
background-color: var(--message-info-bg);
|
||||||
|
background-image: var(--message-info-icon);
|
||||||
|
background-position: 40px 12px;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-size: 16px auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul.messagelist li.debug {
|
||||||
|
background-color: var(--message-debug-bg);
|
||||||
|
background-image: var(--message-debug-icon);
|
||||||
|
}
|
||||||
|
|
||||||
|
ul.messagelist li.info {
|
||||||
|
background-color: var(--message-info-bg);
|
||||||
|
background-image: var(--message-info-icon);
|
||||||
|
}
|
||||||
|
|
||||||
|
ul.messagelist li.success {
|
||||||
|
background-color: var(--message-success-bg);
|
||||||
|
background-image: var(--message-success-icon);
|
||||||
}
|
}
|
||||||
|
|
||||||
ul.messagelist li.warning {
|
ul.messagelist li.warning {
|
||||||
background: var(--message-warning-bg) url(../img/icon-alert.svg) 40px 14px no-repeat;
|
background-color: var(--message-warning-bg);
|
||||||
background-size: 14px auto;
|
background-image: var(--message-warning-icon);
|
||||||
}
|
}
|
||||||
|
|
||||||
ul.messagelist li.error {
|
ul.messagelist li.error {
|
||||||
background: var(--message-error-bg) url(../img/icon-no.svg) 40px 12px no-repeat;
|
background-color: var(--message-error-bg);
|
||||||
background-size: 16px auto;
|
background-image: var(--message-error-icon);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (forced-colors: active) {
|
||||||
|
ul.messagelist li {
|
||||||
|
border: 1px solid;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.errornote {
|
.errornote {
|
||||||
@@ -768,19 +809,19 @@ a.deletelink:focus, a.deletelink:hover {
|
|||||||
/* OBJECT TOOLS */
|
/* OBJECT TOOLS */
|
||||||
|
|
||||||
.object-tools {
|
.object-tools {
|
||||||
font-size: 0.625rem;
|
padding: 0;
|
||||||
font-weight: bold;
|
overflow: hidden;
|
||||||
padding-left: 0;
|
text-align: right;
|
||||||
float: right;
|
margin: 0 0 15px;
|
||||||
position: relative;
|
|
||||||
margin-top: -48px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.object-tools li {
|
.object-tools li {
|
||||||
display: block;
|
display: inline-block;
|
||||||
float: left;
|
height: auto;
|
||||||
margin-left: 5px;
|
}
|
||||||
height: 1rem;
|
|
||||||
|
.object-tools li + li {
|
||||||
|
margin-left: 15px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.object-tools a {
|
.object-tools a {
|
||||||
@@ -1120,39 +1161,40 @@ a.deletelink:focus, a.deletelink:hover {
|
|||||||
line-height: 22px;
|
line-height: 22px;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
border-top: 1px solid var(--hairline-color);
|
border-top: 1px solid var(--hairline-color);
|
||||||
width: 100%;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.paginator a:link, .paginator a:visited {
|
.paginator ul {
|
||||||
|
margin: 0;
|
||||||
|
margin-right: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.paginator ul li {
|
||||||
|
display: inline-block;
|
||||||
|
line-height: 22px;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.paginator a {
|
||||||
|
display: inline-block;
|
||||||
padding: 2px 6px;
|
padding: 2px 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.paginator a:not(.showall) {
|
||||||
background: var(--button-bg);
|
background: var(--button-bg);
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
color: var(--button-fg);
|
color: var(--button-fg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.paginator a.showall {
|
.paginator a[aria-current="page"] {
|
||||||
border: none;
|
color: var(--body-quiet-color);
|
||||||
background: none;
|
background: transparent;
|
||||||
color: var(--link-fg);
|
|
||||||
}
|
|
||||||
|
|
||||||
.paginator a.showall:focus, .paginator a.showall:hover {
|
|
||||||
background: none;
|
|
||||||
color: var(--link-hover-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.paginator .end {
|
|
||||||
margin-right: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.paginator .this-page {
|
|
||||||
padding: 2px 6px;
|
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
font-size: 0.8125rem;
|
cursor: default;
|
||||||
vertical-align: top;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.paginator a:focus, .paginator a:hover {
|
.paginator a:not([aria-current="page"], .showall):focus,
|
||||||
|
.paginator a:not([aria-current="page"], .showall):hover {
|
||||||
color: white;
|
color: white;
|
||||||
background: var(--link-hover-color);
|
background: var(--link-hover-color);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
/* CHANGELISTS */
|
/* CHANGELISTS */
|
||||||
|
|
||||||
#changelist {
|
#changelist .changelist-form-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
justify-content: space-between;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
#changelist .changelist-form-container {
|
#changelist .changelist-form-container > div {
|
||||||
flex: 1 1 auto;
|
flex: 1 1 auto;
|
||||||
min-width: 0;
|
}
|
||||||
|
|
||||||
|
#changelist .changelist-form-container:not(:has(#changelist-filter)) > div {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
#changelist .changelist-form-container:has(#changelist-filter) > div {
|
||||||
|
max-width: calc(100% - 270px);
|
||||||
}
|
}
|
||||||
|
|
||||||
#changelist table {
|
#changelist table {
|
||||||
@@ -25,8 +33,8 @@
|
|||||||
min-height: 400px;
|
min-height: 400px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.change-list .filtered .results, .change-list .filtered .paginator,
|
.change-list .filtered .results, .filtered #toolbar,
|
||||||
.filtered #toolbar, .filtered div.xfull {
|
.filtered div.xfull {
|
||||||
width: auto;
|
width: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,11 +51,31 @@
|
|||||||
border-bottom: 1px solid var(--hairline-color);
|
border-bottom: 1px solid var(--hairline-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#changelist .changelist-footer {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 10px;
|
||||||
|
border-top: 1px solid var(--hairline-color);
|
||||||
|
border-bottom: 1px solid var(--hairline-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
#changelist .changelist-footer .paginator {
|
||||||
|
color: var(--body-quiet-color);
|
||||||
|
background: var(--body-bg);
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
#changelist .paginator {
|
#changelist .paginator {
|
||||||
color: var(--body-quiet-color);
|
color: var(--body-quiet-color);
|
||||||
border-bottom: 1px solid var(--hairline-color);
|
border-bottom: 1px solid var(--hairline-color);
|
||||||
background: var(--body-bg);
|
background: var(--body-bg);
|
||||||
overflow: hidden;
|
}
|
||||||
|
|
||||||
|
#changelist .paginator ul {
|
||||||
|
padding: 0;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* CHANGELIST TABLES */
|
/* CHANGELIST TABLES */
|
||||||
|
|||||||
@@ -20,9 +20,17 @@
|
|||||||
--border-color: #353535;
|
--border-color: #353535;
|
||||||
|
|
||||||
--error-fg: #e35f5f;
|
--error-fg: #e35f5f;
|
||||||
|
|
||||||
|
--message-debug-bg: #4e4e4e;
|
||||||
|
--message-debug-icon: url(../img/icon-debug-dark.svg);
|
||||||
|
--message-info-bg: #265895;
|
||||||
|
--message-info-icon: url(../img/icon-info-dark.svg);
|
||||||
--message-success-bg: #006b1b;
|
--message-success-bg: #006b1b;
|
||||||
|
--message-success-icon: url(../img/icon-yes-dark.svg);
|
||||||
--message-warning-bg: #583305;
|
--message-warning-bg: #583305;
|
||||||
|
--message-warning-icon: url(../img/icon-alert-dark.svg);
|
||||||
--message-error-bg: #570808;
|
--message-error-bg: #570808;
|
||||||
|
--message-error-icon: url(../img/icon-no-dark.svg);
|
||||||
|
|
||||||
--darkened-bg: #212121;
|
--darkened-bg: #212121;
|
||||||
--selected-bg: #1b1b1b;
|
--selected-bg: #1b1b1b;
|
||||||
@@ -57,9 +65,17 @@ html[data-theme="dark"] {
|
|||||||
--border-color: #353535;
|
--border-color: #353535;
|
||||||
|
|
||||||
--error-fg: #e35f5f;
|
--error-fg: #e35f5f;
|
||||||
|
|
||||||
|
--message-debug-bg: #4e4e4e;
|
||||||
|
--message-debug-icon: url(../img/icon-debug-dark.svg);
|
||||||
|
--message-info-bg: #265895;
|
||||||
|
--message-info-icon: url(../img/icon-info-dark.svg);
|
||||||
--message-success-bg: #006b1b;
|
--message-success-bg: #006b1b;
|
||||||
|
--message-success-icon: url(../img/icon-yes-dark.svg);
|
||||||
--message-warning-bg: #583305;
|
--message-warning-bg: #583305;
|
||||||
|
--message-warning-icon: url(../img/icon-alert-dark.svg);
|
||||||
--message-error-bg: #570808;
|
--message-error-bg: #570808;
|
||||||
|
--message-error-icon: url(../img/icon-no-dark.svg);
|
||||||
|
|
||||||
--darkened-bg: #212121;
|
--darkened-bg: #212121;
|
||||||
--selected-bg: #1b1b1b;
|
--selected-bg: #1b1b1b;
|
||||||
@@ -84,8 +100,8 @@ html[data-theme="dark"] {
|
|||||||
|
|
||||||
.theme-toggle svg {
|
.theme-toggle svg {
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
height: 1rem;
|
height: 1.5rem;
|
||||||
width: 1rem;
|
width: 1.5rem;
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,12 +36,13 @@ form .form-row p {
|
|||||||
|
|
||||||
/* FORM LABELS */
|
/* FORM LABELS */
|
||||||
|
|
||||||
label {
|
legend, label {
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
color: var(--body-quiet-color);
|
color: var(--body-quiet-color);
|
||||||
font-size: 0.8125rem;
|
font-size: 0.8125rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.required legend, legend.required,
|
||||||
.required label, label.required {
|
.required label, label.required {
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
}
|
}
|
||||||
@@ -91,6 +92,20 @@ fieldset .inline-heading,
|
|||||||
|
|
||||||
/* ALIGNED FIELDSETS */
|
/* ALIGNED FIELDSETS */
|
||||||
|
|
||||||
|
.aligned fieldset {
|
||||||
|
width: 100%;
|
||||||
|
border-top: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.aligned fieldset > div {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.aligned legend {
|
||||||
|
float: inline-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.aligned legend,
|
||||||
.aligned label {
|
.aligned label {
|
||||||
display: block;
|
display: block;
|
||||||
padding: 4px 10px 0 0;
|
padding: 4px 10px 0 0;
|
||||||
@@ -133,7 +148,7 @@ form .aligned ul {
|
|||||||
}
|
}
|
||||||
|
|
||||||
form .aligned div.radiolist {
|
form .aligned div.radiolist {
|
||||||
display: inline-block;
|
display: block;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
@@ -169,6 +184,10 @@ form .aligned select + div.help {
|
|||||||
padding-left: 10px;
|
padding-left: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
form .aligned select option:checked {
|
||||||
|
background-color: var(--selected-row);
|
||||||
|
}
|
||||||
|
|
||||||
form .aligned ul li {
|
form .aligned ul li {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
}
|
}
|
||||||
@@ -334,7 +353,7 @@ body.popup .submit-row {
|
|||||||
width: 48em;
|
width: 48em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.flatpages-flatpage #id_content {
|
.app-flatpages.model-flatpage #id_content {
|
||||||
height: 40.2em;
|
height: 40.2em;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,9 +428,12 @@ body.popup .submit-row {
|
|||||||
border: none;
|
border: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.inline-related.tabular div.wrapper {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
.inline-related.tabular fieldset.module table {
|
.inline-related.tabular fieldset.module table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
overflow-x: scroll;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.last-related fieldset {
|
.last-related fieldset {
|
||||||
@@ -425,7 +447,6 @@ body.popup .submit-row {
|
|||||||
.inline-group .tabular tr td.original {
|
.inline-group .tabular tr td.original {
|
||||||
padding: 2px 0 0 0;
|
padding: 2px 0 0 0;
|
||||||
width: 0;
|
width: 0;
|
||||||
_position: relative;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.inline-group .tabular th.original {
|
.inline-group .tabular th.original {
|
||||||
@@ -433,27 +454,19 @@ body.popup .submit-row {
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.inline-group .tabular td {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
.inline-group .tabular td.original p {
|
.inline-group .tabular td.original p {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
left: 0;
|
left: 0;
|
||||||
height: 1.1em;
|
height: 1.2em;
|
||||||
padding: 2px 9px;
|
padding: 2px 9px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
font-size: 0.5625rem;
|
font-size: 0.875rem;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
color: var(--body-quiet-color);
|
color: var(--body-quiet-color);
|
||||||
_width: 700px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.inline-group ul.tools {
|
|
||||||
padding: 0;
|
|
||||||
margin: 0;
|
|
||||||
list-style: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.inline-group ul.tools li {
|
|
||||||
display: inline;
|
|
||||||
padding: 0 5px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.inline-group div.add-row,
|
.inline-group div.add-row,
|
||||||
@@ -469,11 +482,8 @@ body.popup .submit-row {
|
|||||||
border-bottom: 1px solid var(--hairline-color);
|
border-bottom: 1px solid var(--hairline-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
.inline-group ul.tools a.add,
|
|
||||||
.inline-group div.add-row a,
|
.inline-group div.add-row a,
|
||||||
.inline-group .tabular tr.add-row td a {
|
.inline-group .tabular tr.add-row td a {
|
||||||
background: url(../img/icon-addlink.svg) 0 1px no-repeat;
|
|
||||||
padding-left: 16px;
|
|
||||||
font-size: 0.75rem;
|
font-size: 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -170,6 +170,7 @@ input[type="submit"], button {
|
|||||||
|
|
||||||
/* Forms */
|
/* Forms */
|
||||||
|
|
||||||
|
legend,
|
||||||
label {
|
label {
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
}
|
}
|
||||||
@@ -254,10 +255,6 @@ input[type="submit"], button {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector .selector-filter label {
|
|
||||||
margin: 0 8px 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.selector .selector-filter input {
|
.selector .selector-filter input {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
@@ -277,29 +274,7 @@ input[type="submit"], button {
|
|||||||
margin-bottom: 5px;
|
margin-bottom: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector ul.selector-chooser {
|
.selector-chooseall, .selector-clearall {
|
||||||
width: 26px;
|
|
||||||
height: 52px;
|
|
||||||
padding: 2px 0;
|
|
||||||
border-radius: 20px;
|
|
||||||
transform: translateY(-10px);
|
|
||||||
}
|
|
||||||
|
|
||||||
.selector-add, .selector-remove {
|
|
||||||
width: 20px;
|
|
||||||
height: 20px;
|
|
||||||
background-size: 20px auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.selector-add {
|
|
||||||
background-position: 0 -120px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.selector-remove {
|
|
||||||
background-position: 0 -80px;
|
|
||||||
}
|
|
||||||
|
|
||||||
a.selector-chooseall, a.selector-clearall {
|
|
||||||
align-self: center;
|
align-self: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -321,8 +296,6 @@ input[type="submit"], button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.stacked ul.selector-chooser {
|
.stacked ul.selector-chooser {
|
||||||
width: 52px;
|
|
||||||
height: 26px;
|
|
||||||
padding: 0 2px;
|
padding: 0 2px;
|
||||||
transform: none;
|
transform: none;
|
||||||
}
|
}
|
||||||
@@ -331,42 +304,6 @@ input[type="submit"], button {
|
|||||||
padding: 3px;
|
padding: 3px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stacked .selector-add, .stacked .selector-remove {
|
|
||||||
background-size: 20px auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stacked .selector-add {
|
|
||||||
background-position: 0 -40px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stacked .active.selector-add {
|
|
||||||
background-position: 0 -40px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.active.selector-add:focus, .active.selector-add:hover {
|
|
||||||
background-position: 0 -140px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stacked .active.selector-add:focus, .stacked .active.selector-add:hover {
|
|
||||||
background-position: 0 -60px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stacked .selector-remove {
|
|
||||||
background-position: 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stacked .active.selector-remove {
|
|
||||||
background-position: 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.active.selector-remove:focus, .active.selector-remove:hover {
|
|
||||||
background-position: 0 -100px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stacked .active.selector-remove:focus, .stacked .active.selector-remove:hover {
|
|
||||||
background-position: 0 -20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.help-tooltip, .selector .help-icon {
|
.help-tooltip, .selector .help-icon {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
@@ -401,16 +338,8 @@ input[type="submit"], button {
|
|||||||
/* Messages */
|
/* Messages */
|
||||||
|
|
||||||
ul.messagelist li {
|
ul.messagelist li {
|
||||||
padding-left: 55px;
|
padding: 10px 10px 10px 55px;
|
||||||
background-position: 30px 12px;
|
background-position-x: 30px;
|
||||||
}
|
|
||||||
|
|
||||||
ul.messagelist li.error {
|
|
||||||
background-position: 30px 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
ul.messagelist li.warning {
|
|
||||||
background-position: 30px 14px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Login */
|
/* Login */
|
||||||
@@ -481,11 +410,15 @@ input[type="submit"], button {
|
|||||||
|
|
||||||
/* Changelist */
|
/* Changelist */
|
||||||
|
|
||||||
#changelist {
|
#changelist .changelist-form-container {
|
||||||
align-items: stretch;
|
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#changelist .changelist-form-container:has(#changelist-filter) > div {
|
||||||
|
max-width: 100%;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
#toolbar {
|
#toolbar {
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
}
|
}
|
||||||
@@ -508,25 +441,12 @@ input[type="submit"], button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#changelist-filter {
|
#changelist-filter {
|
||||||
position: static;
|
width: 100%;
|
||||||
width: auto;
|
|
||||||
margin-top: 30px;
|
margin-top: 30px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.object-tools {
|
.object-tools {
|
||||||
float: none;
|
text-align: left;
|
||||||
margin: 0 0 15px;
|
|
||||||
padding: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.object-tools li {
|
|
||||||
height: auto;
|
|
||||||
margin-left: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.object-tools li + li {
|
|
||||||
margin-left: 15px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Forms */
|
/* Forms */
|
||||||
@@ -565,6 +485,7 @@ input[type="submit"], button {
|
|||||||
padding-top: 15px;
|
padding-top: 15px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.aligned legend,
|
||||||
.aligned label {
|
.aligned label {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-width: auto;
|
min-width: auto;
|
||||||
@@ -639,6 +560,10 @@ input[type="submit"], button {
|
|||||||
margin-top: 5px;
|
margin-top: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
form .aligned fieldset div.flex-container {
|
||||||
|
display: unset;
|
||||||
|
}
|
||||||
|
|
||||||
/* Related widget */
|
/* Related widget */
|
||||||
|
|
||||||
.related-widget-wrapper {
|
.related-widget-wrapper {
|
||||||
@@ -649,6 +574,7 @@ input[type="submit"], button {
|
|||||||
|
|
||||||
.related-widget-wrapper .selector {
|
.related-widget-wrapper .selector {
|
||||||
order: 1;
|
order: 1;
|
||||||
|
flex: 1 0 auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.related-widget-wrapper > a {
|
.related-widget-wrapper > a {
|
||||||
@@ -679,9 +605,9 @@ input[type="submit"], button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.selector ul.selector-chooser {
|
.selector ul.selector-chooser {
|
||||||
display: block;
|
display: flex;
|
||||||
width: 52px;
|
width: 60px;
|
||||||
height: 26px;
|
height: 30px;
|
||||||
padding: 0 2px;
|
padding: 0 2px;
|
||||||
transform: none;
|
transform: none;
|
||||||
}
|
}
|
||||||
@@ -694,16 +620,16 @@ input[type="submit"], button {
|
|||||||
background-position: 0 0;
|
background-position: 0 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-remove:focus, .active.selector-remove:hover {
|
:enabled.selector-remove:focus, :enabled.selector-remove:hover {
|
||||||
background-position: 0 -20px;
|
background-position: 0 -24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector-add {
|
.selector-add {
|
||||||
background-position: 0 -40px;
|
background-position: 0 -48px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-add:focus, .active.selector-add:hover {
|
:enabled.selector-add:focus, :enabled.selector-add:hover {
|
||||||
background-position: 0 -60px;
|
background-position: 0 -72px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Inlines */
|
/* Inlines */
|
||||||
@@ -802,16 +728,8 @@ input[type="submit"], button {
|
|||||||
/* Messages */
|
/* Messages */
|
||||||
|
|
||||||
ul.messagelist li {
|
ul.messagelist li {
|
||||||
padding-left: 40px;
|
padding: 10px 10px 10px 40px;
|
||||||
background-position: 15px 12px;
|
background-position-x: 15px;
|
||||||
}
|
|
||||||
|
|
||||||
ul.messagelist li.error {
|
|
||||||
background-position: 15px 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
ul.messagelist li.warning {
|
|
||||||
background-position: 15px 14px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Paginator */
|
/* Paginator */
|
||||||
|
|||||||
@@ -28,46 +28,20 @@
|
|||||||
margin-left: 0;
|
margin-left: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
[dir="rtl"] .inline-group ul.tools a.add,
|
|
||||||
[dir="rtl"] .inline-group div.add-row a,
|
[dir="rtl"] .inline-group div.add-row a,
|
||||||
[dir="rtl"] .inline-group .tabular tr.add-row td a {
|
[dir="rtl"] .inline-group .tabular tr.add-row td a {
|
||||||
padding: 8px 26px 8px 10px;
|
padding: 8px 26px 8px 10px;
|
||||||
background-position: calc(100% - 8px) 9px;
|
background-position: calc(100% - 8px) 9px;
|
||||||
}
|
}
|
||||||
|
|
||||||
[dir="rtl"] .selector .selector-filter label {
|
|
||||||
margin-right: 0;
|
|
||||||
margin-left: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
[dir="rtl"] .object-tools li {
|
|
||||||
float: right;
|
|
||||||
}
|
|
||||||
|
|
||||||
[dir="rtl"] .object-tools li + li {
|
|
||||||
margin-left: 0;
|
|
||||||
margin-right: 15px;
|
|
||||||
}
|
|
||||||
|
|
||||||
[dir="rtl"] .dashboard .module table td a {
|
[dir="rtl"] .dashboard .module table td a {
|
||||||
padding-left: 0;
|
padding-left: 0;
|
||||||
padding-right: 16px;
|
padding-right: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
[dir="rtl"] .selector-add {
|
[dir="rtl"] ul.messagelist li {
|
||||||
background-position: 0 -80px;
|
padding: 10px 55px 10px 10px;
|
||||||
}
|
background-position-x: calc(100% - 30px);
|
||||||
|
|
||||||
[dir="rtl"] .selector-remove {
|
|
||||||
background-position: 0 -120px;
|
|
||||||
}
|
|
||||||
|
|
||||||
[dir="rtl"] .active.selector-add:focus, .active.selector-add:hover {
|
|
||||||
background-position: 0 -100px;
|
|
||||||
}
|
|
||||||
|
|
||||||
[dir="rtl"] .active.selector-remove:focus, .active.selector-remove:hover {
|
|
||||||
background-position: 0 -140px;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +63,11 @@
|
|||||||
margin-left: 0;
|
margin-left: 0;
|
||||||
margin-right: 0;
|
margin-right: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[dir="rtl"] .object-tools {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
[dir="rtl"] .aligned .vCheckboxLabel {
|
[dir="rtl"] .aligned .vCheckboxLabel {
|
||||||
padding: 1px 5px 0 0;
|
padding: 1px 5px 0 0;
|
||||||
}
|
}
|
||||||
@@ -97,15 +76,20 @@
|
|||||||
background-position: 0 0;
|
background-position: 0 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
[dir="rtl"] .active.selector-remove:focus, .active.selector-remove:hover {
|
[dir="rtl"] :enabled.selector-remove:focus, :enabled.selector-remove:hover {
|
||||||
background-position: 0 -20px;
|
background-position: 0 -24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
[dir="rtl"] .selector-add {
|
[dir="rtl"] .selector-add {
|
||||||
background-position: 0 -40px;
|
background-position: 0 -48px;
|
||||||
}
|
}
|
||||||
|
|
||||||
[dir="rtl"] .active.selector-add:focus, .active.selector-add:hover {
|
[dir="rtl"] :enabled.selector-add:focus, :enabled.selector-add:hover {
|
||||||
background-position: 0 -60px;
|
background-position: 0 -72px;
|
||||||
|
}
|
||||||
|
|
||||||
|
[dir="rtl"] ul.messagelist li {
|
||||||
|
padding: 10px 40px 10px 10px;
|
||||||
|
background-position-x: calc(100% - 15px);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,12 @@ th {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.object-tools {
|
.object-tools {
|
||||||
float: left;
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.object-tools li + li {
|
||||||
|
margin-right: 15px;
|
||||||
|
margin-left: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
thead th:first-child,
|
thead th:first-child,
|
||||||
@@ -107,7 +112,7 @@ thead th.sorted .text {
|
|||||||
border-left: none;
|
border-left: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.paginator .end {
|
.paginator ul {
|
||||||
margin-left: 6px;
|
margin-left: 6px;
|
||||||
margin-right: 0;
|
margin-right: 0;
|
||||||
}
|
}
|
||||||
@@ -220,34 +225,28 @@ fieldset .fieldBox {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.selector-add {
|
.selector-add {
|
||||||
background: url(../img/selector-icons.svg) 0 -64px no-repeat;
|
background: url(../img/selector-icons.svg) 0 -96px no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-add:focus, .active.selector-add:hover {
|
:enabled.selector-add:focus, :enabled.selector-add:hover {
|
||||||
background-position: 0 -80px;
|
background-position: 0 -120px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector-remove {
|
.selector-remove {
|
||||||
background: url(../img/selector-icons.svg) 0 -96px no-repeat;
|
background: url(../img/selector-icons.svg) 0 -144px no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-remove:focus, .active.selector-remove:hover {
|
:enabled.selector-remove:focus, :enabled.selector-remove:hover {
|
||||||
background-position: 0 -112px;
|
background-position: 0 -168px;
|
||||||
}
|
}
|
||||||
|
|
||||||
a.selector-chooseall {
|
:enabled.selector-chooseall:focus, :enabled.selector-chooseall:hover {
|
||||||
background: url(../img/selector-icons.svg) right -128px no-repeat;
|
|
||||||
}
|
|
||||||
|
|
||||||
a.active.selector-chooseall:focus, a.active.selector-chooseall:hover {
|
|
||||||
background-position: 100% -144px;
|
background-position: 100% -144px;
|
||||||
}
|
}
|
||||||
|
|
||||||
a.selector-clearall {
|
:enabled.selector-clearall:focus, :enabled.selector-clearall:hover {
|
||||||
background: url(../img/selector-icons.svg) 0 -160px no-repeat;
|
|
||||||
}
|
|
||||||
|
|
||||||
a.active.selector-clearall:focus, a.active.selector-clearall:hover {
|
|
||||||
background-position: 0 -176px;
|
background-position: 0 -176px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,3 +288,8 @@ form .form-row p.datetime {
|
|||||||
.selector .selector-chooser {
|
.selector .selector-chooser {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ul.messagelist li {
|
||||||
|
padding: 10px 65px 10px 10px;
|
||||||
|
background-position-x: calc(100% - 40px);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
.selector {
|
.selector {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-grow: 1;
|
flex: 1;
|
||||||
gap: 0 10px;
|
gap: 0 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14,17 +14,20 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.selector-available, .selector-chosen {
|
.selector-available, .selector-chosen {
|
||||||
text-align: center;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
flex: 1 1;
|
flex: 1 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector-available h2, .selector-chosen h2 {
|
.selector-available-title, .selector-chosen-title {
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
border-radius: 4px 4px 0 0;
|
border-radius: 4px 4px 0 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.selector .helptext {
|
||||||
|
font-size: 0.6875rem;
|
||||||
|
}
|
||||||
|
|
||||||
.selector-chosen .list-footer-display {
|
.selector-chosen .list-footer-display {
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
border-top: none;
|
border-top: none;
|
||||||
@@ -40,14 +43,25 @@
|
|||||||
color: var(--breadcrumbs-fg);
|
color: var(--breadcrumbs-fg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector-chosen h2 {
|
.selector-chosen-title {
|
||||||
background: var(--secondary);
|
background: var(--secondary);
|
||||||
color: var(--header-link-color);
|
color: var(--header-link-color);
|
||||||
|
padding: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector .selector-available h2 {
|
.selector-chosen-title label {
|
||||||
|
color: var(--header-link-color);
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.selector-available-title {
|
||||||
background: var(--darkened-bg);
|
background: var(--darkened-bg);
|
||||||
color: var(--body-quiet-color);
|
color: var(--body-quiet-color);
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.selector-available-title label {
|
||||||
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector .selector-filter {
|
.selector .selector-filter {
|
||||||
@@ -59,6 +73,7 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector .selector-filter label,
|
.selector .selector-filter label,
|
||||||
@@ -77,14 +92,9 @@
|
|||||||
flex-grow: 1;
|
flex-grow: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector .selector-available input,
|
|
||||||
.selector .selector-chosen input {
|
|
||||||
margin-left: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.selector ul.selector-chooser {
|
.selector ul.selector-chooser {
|
||||||
align-self: center;
|
align-self: center;
|
||||||
width: 22px;
|
width: 30px;
|
||||||
background-color: var(--selected-bg);
|
background-color: var(--selected-bg);
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
@@ -114,82 +124,74 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.selector-add, .selector-remove {
|
.selector-add, .selector-remove {
|
||||||
width: 16px;
|
width: 24px;
|
||||||
height: 16px;
|
height: 24px;
|
||||||
display: block;
|
display: block;
|
||||||
text-indent: -3000px;
|
text-indent: -3000px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
cursor: default;
|
cursor: default;
|
||||||
opacity: 0.55;
|
opacity: 0.55;
|
||||||
|
border: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-add, .active.selector-remove {
|
:enabled.selector-add, :enabled.selector-remove {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-add:hover, .active.selector-remove:hover {
|
:enabled.selector-add:hover, :enabled.selector-remove:hover {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector-add {
|
.selector-add {
|
||||||
background: url(../img/selector-icons.svg) 0 -96px no-repeat;
|
background: url(../img/selector-icons.svg) 0 -144px no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-add:focus, .active.selector-add:hover {
|
:enabled.selector-add:focus, :enabled.selector-add:hover {
|
||||||
background-position: 0 -112px;
|
background-position: 0 -168px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.selector-remove {
|
.selector-remove {
|
||||||
background: url(../img/selector-icons.svg) 0 -64px no-repeat;
|
background: url(../img/selector-icons.svg) 0 -96px no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.active.selector-remove:focus, .active.selector-remove:hover {
|
:enabled.selector-remove:focus, :enabled.selector-remove:hover {
|
||||||
background-position: 0 -80px;
|
background-position: 0 -120px;
|
||||||
}
|
}
|
||||||
|
|
||||||
a.selector-chooseall, a.selector-clearall {
|
.selector-chooseall, .selector-clearall {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
height: 16px;
|
|
||||||
text-align: left;
|
text-align: left;
|
||||||
|
padding: 4px 5px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
font-weight: bold;
|
color: var(--button-fg);
|
||||||
line-height: 16px;
|
background-color: var(--button-bg);
|
||||||
color: var(--body-quiet-color);
|
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
opacity: 0.55;
|
opacity: 0.55;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
a.active.selector-chooseall:focus, a.active.selector-clearall:focus,
|
:enabled.selector-chooseall:focus, :enabled.selector-clearall:focus,
|
||||||
a.active.selector-chooseall:hover, a.active.selector-clearall:hover {
|
:enabled.selector-chooseall:hover, :enabled.selector-clearall:hover {
|
||||||
color: var(--link-fg);
|
background-color: var(--button-hover-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
a.active.selector-chooseall, a.active.selector-clearall {
|
:enabled.selector-chooseall, :enabled.selector-clearall {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
a.active.selector-chooseall:hover, a.active.selector-clearall:hover {
|
:enabled.selector-chooseall:hover, :enabled.selector-clearall:hover {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
a.selector-chooseall {
|
:enabled.selector-chooseall:focus, :enabled.selector-chooseall:hover {
|
||||||
padding: 0 18px 0 0;
|
|
||||||
background: url(../img/selector-icons.svg) right -160px no-repeat;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
a.active.selector-chooseall:focus, a.active.selector-chooseall:hover {
|
|
||||||
background-position: 100% -176px;
|
background-position: 100% -176px;
|
||||||
}
|
}
|
||||||
|
|
||||||
a.selector-clearall {
|
:enabled.selector-clearall:focus, :enabled.selector-clearall:hover {
|
||||||
padding: 0 0 0 18px;
|
|
||||||
background: url(../img/selector-icons.svg) 0 -128px no-repeat;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
a.active.selector-clearall:focus, a.active.selector-clearall:hover {
|
|
||||||
background-position: 0 -144px;
|
background-position: 0 -144px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,8 +221,9 @@ a.active.selector-clearall:focus, a.active.selector-clearall:hover {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.stacked ul.selector-chooser {
|
.stacked ul.selector-chooser {
|
||||||
height: 22px;
|
display: flex;
|
||||||
width: 50px;
|
height: 30px;
|
||||||
|
width: 64px;
|
||||||
margin: 0 0 10px 40%;
|
margin: 0 0 10px 40%;
|
||||||
background-color: #eee;
|
background-color: #eee;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
@@ -237,32 +240,34 @@ a.active.selector-clearall:focus, a.active.selector-clearall:hover {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.stacked .selector-add {
|
.stacked .selector-add {
|
||||||
background: url(../img/selector-icons.svg) 0 -32px no-repeat;
|
background: url(../img/selector-icons.svg) 0 -48px no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
cursor: default;
|
cursor: default;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stacked .active.selector-add {
|
.stacked :enabled.selector-add {
|
||||||
background-position: 0 -32px;
|
background-position: 0 -48px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stacked .active.selector-add:focus, .stacked .active.selector-add:hover {
|
.stacked :enabled.selector-add:focus, .stacked :enabled.selector-add:hover {
|
||||||
background-position: 0 -48px;
|
background-position: 0 -72px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stacked .selector-remove {
|
.stacked .selector-remove {
|
||||||
background: url(../img/selector-icons.svg) 0 0 no-repeat;
|
background: url(../img/selector-icons.svg) 0 0 no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
cursor: default;
|
cursor: default;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stacked .active.selector-remove {
|
.stacked :enabled.selector-remove {
|
||||||
background-position: 0 0px;
|
background-position: 0 0px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stacked .active.selector-remove:focus, .stacked .active.selector-remove:hover {
|
.stacked :enabled.selector-remove:focus, .stacked :enabled.selector-remove:hover {
|
||||||
background-position: 0 -16px;
|
background-position: 0 -24px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,6 +301,10 @@ p.datetime {
|
|||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
p.datetime label {
|
||||||
|
display: inline;
|
||||||
|
}
|
||||||
|
|
||||||
.datetime span {
|
.datetime span {
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
@@ -318,28 +327,30 @@ table p.datetime {
|
|||||||
position: relative;
|
position: relative;
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
height: 16px;
|
height: 24px;
|
||||||
width: 16px;
|
width: 24px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.datetimeshortcuts .clock-icon {
|
.datetimeshortcuts .clock-icon {
|
||||||
background: url(../img/icon-clock.svg) 0 0 no-repeat;
|
background: url(../img/icon-clock.svg) 0 0 no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.datetimeshortcuts a:focus .clock-icon,
|
.datetimeshortcuts a:focus .clock-icon,
|
||||||
.datetimeshortcuts a:hover .clock-icon {
|
.datetimeshortcuts a:hover .clock-icon {
|
||||||
background-position: 0 -16px;
|
background-position: 0 -24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.datetimeshortcuts .date-icon {
|
.datetimeshortcuts .date-icon {
|
||||||
background: url(../img/icon-calendar.svg) 0 0 no-repeat;
|
background: url(../img/icon-calendar.svg) 0 0 no-repeat;
|
||||||
|
background-size: 24px auto;
|
||||||
top: -1px;
|
top: -1px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.datetimeshortcuts a:focus .date-icon,
|
.datetimeshortcuts a:focus .date-icon,
|
||||||
.datetimeshortcuts a:hover .date-icon {
|
.datetimeshortcuts a:hover .date-icon {
|
||||||
background-position: 0 -16px;
|
background-position: 0 -24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.timezonewarning {
|
.timezonewarning {
|
||||||
@@ -557,10 +568,12 @@ ul.timelist, .timelist li {
|
|||||||
.inline-deletelink {
|
.inline-deletelink {
|
||||||
float: right;
|
float: right;
|
||||||
text-indent: -9999px;
|
text-indent: -9999px;
|
||||||
background: url(../img/inline-delete.svg) 0 0 no-repeat;
|
background: url(../img/inline-delete.svg) center center no-repeat;
|
||||||
width: 16px;
|
background-size: contain;
|
||||||
height: 16px;
|
width: 1.5rem;
|
||||||
|
height: 1.5rem;
|
||||||
border: 0px none;
|
border: 0px none;
|
||||||
|
margin-bottom: .25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.inline-deletelink:focus, .inline-deletelink:hover {
|
.inline-deletelink:focus, .inline-deletelink:hover {
|
||||||
|
|||||||
80
app/static/admin/img/README.md
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
# Information about icons in this directory
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
All icons in this directory are provided by
|
||||||
|
[Font Awesome Free](https://fontawesome.com), version 6.7.2.
|
||||||
|
|
||||||
|
- The icons are licensed under the [Creative Commons Attribution 4.0
|
||||||
|
International (CC-BY-4.0)](https://creativecommons.org/licenses/by/4.0/)
|
||||||
|
license.
|
||||||
|
- This license allows you to use, modify, and distribute the icons, provided
|
||||||
|
proper attribution is given.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
- You may use, modify, and distribute the icons in this repository in
|
||||||
|
compliance with the [Creative Commons Attribution 4.0 International
|
||||||
|
(CC-BY-4.0)](https://creativecommons.org/licenses/by/4.0/) license.
|
||||||
|
|
||||||
|
## Modifications
|
||||||
|
|
||||||
|
- These icons have been resized, recolored, or otherwise modified to fit the
|
||||||
|
requirements of this project.
|
||||||
|
|
||||||
|
- These modifications alter the appearance of the original icons but remain
|
||||||
|
covered under the terms of the
|
||||||
|
[CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/) license.
|
||||||
|
|
||||||
|
## Contributing SVG Icons
|
||||||
|
|
||||||
|
To ensure visual consistency, traceability, and proper license attribution,
|
||||||
|
follow these guidelines. This applies when adding or modifying icons.
|
||||||
|
|
||||||
|
## ⚠️ Important: Changing Font Awesome Version
|
||||||
|
|
||||||
|
If you update to a different Font Awesome version, you must **update all SVG
|
||||||
|
files** and **comments inside the files** to reflect the new version number and
|
||||||
|
licensing URL accordingly. For example:
|
||||||
|
|
||||||
|
* Original:
|
||||||
|
```xml
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
```
|
||||||
|
* Updated:
|
||||||
|
```xml
|
||||||
|
<!--!Font Awesome Free X.Y.Z by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright YYYY Fonticons, Inc.-->
|
||||||
|
```
|
||||||
|
|
||||||
|
## Adding a new icon
|
||||||
|
|
||||||
|
1. Use only [Font Awesome Free Icons](https://fontawesome.com/icons).
|
||||||
|
2. Save the icon as an .svg file in this directory.
|
||||||
|
3. Include the following attribution comment at the top of the file (do not
|
||||||
|
change it):
|
||||||
|
```xml
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
```
|
||||||
|
4. Right before the `<path>` element, add the following metadata comment with
|
||||||
|
the appropriate values:
|
||||||
|
```xml
|
||||||
|
<!--
|
||||||
|
Icon Name: [icon-name]
|
||||||
|
Icon Family: [classic | sharp | brands | etc.]
|
||||||
|
Icon Style: [solid | regular | light | thin | duotone | etc.]
|
||||||
|
-->
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example SVG Structure
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: plus
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#5fa225" stroke="#5fa225" stroke-width="30" d="M256 80c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 144L48 224c-17.7 0-32 14.3-32 32s14.3 32 32 32l144 0 0 144c0 17.7 14.3 32 32 32s32-14.3 32-32l0-144 144 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-144 0 0-144z"/>
|
||||||
|
</svg>
|
||||||
|
```
|
||||||
@@ -1,63 +1,44 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
|
||||||
<svg
|
<svg
|
||||||
width="15"
|
width="15"
|
||||||
height="30"
|
height="30"
|
||||||
viewBox="0 0 1792 3584"
|
viewBox="0 0 512 1024"
|
||||||
version="1.1"
|
version="1.1"
|
||||||
id="svg5"
|
id="svg5"
|
||||||
sodipodi:docname="calendar-icons.svg"
|
|
||||||
inkscape:version="1.3.2 (091e20ef0f, 2023-11-25, custom)"
|
|
||||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
|
||||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
|
||||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg">
|
||||||
xmlns:svg="http://www.w3.org/2000/svg">
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
<sodipodi:namedview
|
<defs id="defs2">
|
||||||
id="namedview5"
|
<g id="previous">
|
||||||
pagecolor="#ffffff"
|
<!--
|
||||||
bordercolor="#666666"
|
Icon Name: circle-chevron-left
|
||||||
borderopacity="1.0"
|
Icon Family: classic
|
||||||
inkscape:showpageshadow="2"
|
Icon Style: solid
|
||||||
inkscape:pageopacity="0.0"
|
-->
|
||||||
inkscape:pagecheckerboard="0"
|
|
||||||
inkscape:deskcolor="#d1d1d1"
|
|
||||||
showgrid="false"
|
|
||||||
inkscape:zoom="13.3"
|
|
||||||
inkscape:cx="15.526316"
|
|
||||||
inkscape:cy="20.977444"
|
|
||||||
inkscape:window-width="1920"
|
|
||||||
inkscape:window-height="1011"
|
|
||||||
inkscape:window-x="0"
|
|
||||||
inkscape:window-y="0"
|
|
||||||
inkscape:window-maximized="1"
|
|
||||||
inkscape:current-layer="svg5" />
|
|
||||||
<defs
|
|
||||||
id="defs2">
|
|
||||||
<g
|
|
||||||
id="previous">
|
|
||||||
<path
|
<path
|
||||||
d="m 1037,1395 102,-102 q 19,-19 19,-45 0,-26 -19,-45 L 832,896 1139,589 q 19,-19 19,-45 0,-26 -19,-45 L 1037,397 q -19,-19 -45,-19 -26,0 -45,19 L 493,851 q -19,19 -19,45 0,26 19,45 l 454,454 q 19,19 45,19 26,0 45,-19 z m 627,-499 q 0,209 -103,385.5 Q 1458,1458 1281.5,1561 1105,1664 896,1664 687,1664 510.5,1561 334,1458 231,1281.5 128,1105 128,896 128,687 231,510.5 334,334 510.5,231 687,128 896,128 1105,128 1281.5,231 1458,334 1561,510.5 1664,687 1664,896 Z"
|
d="M512 256A256 256 0 1 0 0 256a256 256 0 1 0 512 0zM271 135c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-87 87 87 87c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0L167 273c-9.4-9.4-9.4-24.6 0-33.9L271 135z"
|
||||||
id="path1" />
|
|
||||||
</g>
|
|
||||||
<g
|
|
||||||
id="next">
|
|
||||||
<path
|
|
||||||
d="m 845,1395 454,-454 q 19,-19 19,-45 0,-26 -19,-45 L 845,397 q -19,-19 -45,-19 -26,0 -45,19 L 653,499 q -19,19 -19,45 0,26 19,45 l 307,307 -307,307 q -19,19 -19,45 0,26 19,45 l 102,102 q 19,19 45,19 26,0 45,-19 z m 819,-499 q 0,209 -103,385.5 Q 1458,1458 1281.5,1561 1105,1664 896,1664 687,1664 510.5,1561 334,1458 231,1281.5 128,1105 128,896 128,687 231,510.5 334,334 510.5,231 687,128 896,128 1105,128 1281.5,231 1458,334 1561,510.5 1664,687 1664,896 Z"
|
|
||||||
id="path2" />
|
id="path2" />
|
||||||
</g>
|
</g>
|
||||||
|
<g id="next">
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-chevron-right
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path
|
||||||
|
d="M0 256a256 256 0 1 0 512 0A256 256 0 1 0 0 256zM241 377c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l87-87-87-87c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0L345 239c9.4 9.4 9.4 24.6 0 33.9L241 377z"
|
||||||
|
id="path1" />
|
||||||
|
</g>
|
||||||
</defs>
|
</defs>
|
||||||
<use
|
<use
|
||||||
xlink:href="#next"
|
xlink:href="#next"
|
||||||
x="0"
|
x="0"
|
||||||
y="5376"
|
y="512"
|
||||||
fill="#000000"
|
fill="#000000"
|
||||||
id="use5"
|
id="use5" />
|
||||||
transform="translate(0,-3584)" />
|
|
||||||
<use
|
<use
|
||||||
xlink:href="#previous"
|
xlink:href="#previous"
|
||||||
x="0"
|
x="0"
|
||||||
y="0"
|
y="0"
|
||||||
fill="#333333"
|
fill="#333333"
|
||||||
id="use2"
|
id="use2" />
|
||||||
style="fill:#000000;fill-opacity:1" />
|
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 1.3 KiB |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">
|
||||||
<path fill="#5fa225" d="M1600 796v192q0 40-28 68t-68 28h-416v416q0 40-28 68t-68 28h-192q-40 0-68-28t-28-68v-416h-416q-40 0-68-28t-28-68v-192q0-40 28-68t68-28h416v-416q0-40 28-68t68-28h192q40 0 68 28t28 68v416h416q40 0 68 28t28 68z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: plus
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#5fa225" stroke="#5fa225" stroke-width="30" d="M256 80c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 144L48 224c-17.7 0-32 14.3-32 32s14.3 32 32 32l144 0 0 144c0 17.7 14.3 32 32 32s32-14.3 32-32l0-144 144 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-144 0 0-144z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 331 B After Width: | Height: | Size: 593 B |
9
app/static/admin/img/icon-alert-dark.svg
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="14" height="14">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: triangle-exclamation
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#efb80b" d="M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480L40 480c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 684 B |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="14" height="14" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="14" height="14">
|
||||||
<path fill="#efb80b" d="M1024 1375v-190q0-14-9.5-23.5t-22.5-9.5h-192q-13 0-22.5 9.5t-9.5 23.5v190q0 14 9.5 23.5t22.5 9.5h192q13 0 22.5-9.5t9.5-23.5zm-2-374l18-459q0-12-10-19-13-11-24-11h-220q-11 0-24 11-10 7-10 21l17 457q0 10 10 16.5t24 6.5h185q14 0 23.5-6.5t10.5-16.5zm-14-934l768 1408q35 63-2 126-17 29-46.5 46t-63.5 17h-1536q-34 0-63.5-17t-46.5-46q-37-63-2-126l768-1408q17-31 47-49t65-18 65 18 47 49z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: triangle-exclamation
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#b78b02" d="M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480L40 480c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 504 B After Width: | Height: | Size: 684 B |
@@ -1,9 +1,15 @@
|
|||||||
<svg width="16" height="32" viewBox="0 0 1792 3584" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
<svg width="16" height="32" viewBox="0 0 448 1024" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
<defs>
|
<defs>
|
||||||
<g id="icon">
|
<g id="icon">
|
||||||
<path d="M192 1664h288v-288h-288v288zm352 0h320v-288h-320v288zm-352-352h288v-320h-288v320zm352 0h320v-320h-320v320zm-352-384h288v-288h-288v288zm736 736h320v-288h-320v288zm-384-736h320v-288h-320v288zm768 736h288v-288h-288v288zm-384-352h320v-320h-320v320zm-352-864v-288q0-13-9.5-22.5t-22.5-9.5h-64q-13 0-22.5 9.5t-9.5 22.5v288q0 13 9.5 22.5t22.5 9.5h64q13 0 22.5-9.5t9.5-22.5zm736 864h288v-320h-288v320zm-384-384h320v-288h-320v288zm384 0h288v-288h-288v288zm32-480v-288q0-13-9.5-22.5t-22.5-9.5h-64q-13 0-22.5 9.5t-9.5 22.5v288q0 13 9.5 22.5t22.5 9.5h64q13 0 22.5-9.5t9.5-22.5zm384-64v1280q0 52-38 90t-90 38h-1408q-52 0-90-38t-38-90v-1280q0-52 38-90t90-38h128v-96q0-66 47-113t113-47h64q66 0 113 47t47 113v96h384v-96q0-66 47-113t113-47h64q66 0 113 47t47 113v96h128q52 0 90 38t38 90z"/>
|
<!--
|
||||||
|
Icon Name: calendar-days
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: regular
|
||||||
|
-->
|
||||||
|
<path d="M152 24c0-13.3-10.7-24-24-24s-24 10.7-24 24l0 40L64 64C28.7 64 0 92.7 0 128l0 16 0 48L0 448c0 35.3 28.7 64 64 64l320 0c35.3 0 64-28.7 64-64l0-256 0-48 0-16c0-35.3-28.7-64-64-64l-40 0 0-40c0-13.3-10.7-24-24-24s-24 10.7-24 24l0 40L152 64l0-40zM48 192l80 0 0 56-80 0 0-56zm0 104l80 0 0 64-80 0 0-64zm128 0l96 0 0 64-96 0 0-64zm144 0l80 0 0 64-80 0 0-64zm80-48l-80 0 0-56 80 0 0 56zm0 160l0 40c0 8.8-7.2 16-16 16l-64 0 0-56 80 0zm-128 0l0 56-96 0 0-56 96 0zm-144 0l0 56-64 0c-8.8 0-16-7.2-16-16l0-40 80 0zM272 248l-96 0 0-56 96 0 0 56z"/>
|
||||||
</g>
|
</g>
|
||||||
</defs>
|
</defs>
|
||||||
<use xlink:href="#icon" x="0" y="0" fill="#447e9b" />
|
<use xlink:href="#icon" x="0" y="0" fill="#447e9b" />
|
||||||
<use xlink:href="#icon" x="0" y="1792" fill="#003366" />
|
<use xlink:href="#icon" x="0" y="512" fill="#003366" />
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.1 KiB |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
<path fill="#b48c08" d="M491 1536l91-91-235-235-91 91v107h128v128h107zm523-928q0-22-22-22-10 0-17 7l-542 542q-7 7-7 17 0 22 22 22 10 0 17-7l542-542q7-7 7-17zm-54-192l416 416-832 832h-416v-416zm683 96q0 53-37 90l-166 166-416-416 166-165q36-38 90-38 53 0 91 38l235 234q37 39 37 91z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: pencil
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#b48c08" d="M410.3 231l11.3-11.3-33.9-33.9-62.1-62.1L291.7 89.8l-11.3 11.3-22.6 22.6L58.6 322.9c-10.4 10.4-18 23.3-22.2 37.4L1 480.7c-2.5 8.4-.2 17.5 6.1 23.7s15.3 8.5 23.7 6.1l120.3-35.4c14.1-4.2 27-11.8 37.4-22.2L387.7 253.7 410.3 231zM160 399.4l-9.1 22.7c-4 3.1-8.5 5.4-13.3 6.9L59.4 452l23-78.1c1.4-4.9 3.8-9.4 6.9-13.3l22.7-9.1 0 32c0 8.8 7.2 16 16 16l32 0zM362.7 18.7L348.3 33.2 325.7 55.8 314.3 67.1l33.9 33.9 62.1 62.1 33.9 33.9 11.3-11.3 22.6-22.6 14.5-14.5c25-25 25-65.5 0-90.5L453.3 18.7c-25-25-65.5-25-90.5 0zm-47.4 168l-144 144c-6.2 6.2-16.4 6.2-22.6 0s-6.2-16.4 0-22.6l144-144c6.2-6.2 16.4-6.2 22.6 0s6.2 16.4 0 22.6z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 380 B After Width: | Height: | Size: 978 B |
@@ -1,9 +1,15 @@
|
|||||||
<svg width="16" height="32" viewBox="0 0 1792 3584" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
<svg width="16" height="32" viewBox="0 0 512 1024" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
<defs>
|
<defs>
|
||||||
<g id="icon">
|
<g id="icon">
|
||||||
<path d="M1024 544v448q0 14-9 23t-23 9h-320q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h224v-352q0-14 9-23t23-9h64q14 0 23 9t9 23zm416 352q0-148-73-273t-198-198-273-73-273 73-198 198-73 273 73 273 198 198 273 73 273-73 198-198 73-273zm224 0q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z"/>
|
<!--
|
||||||
|
Icon Name: clock
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: regular
|
||||||
|
-->
|
||||||
|
<path d="M464 256A208 208 0 1 1 48 256a208 208 0 1 1 416 0zM0 256a256 256 0 1 0 512 0A256 256 0 1 0 0 256zM232 120l0 136c0 8 4 15.5 10.7 20l96 64c11 7.4 25.9 4.4 33.3-6.7s4.4-25.9-6.7-33.3L280 243.2 280 120c0-13.3-10.7-24-24-24s-24 10.7-24 24z"/>
|
||||||
</g>
|
</g>
|
||||||
</defs>
|
</defs>
|
||||||
<use xlink:href="#icon" x="0" y="0" fill="#447e9b" />
|
<use xlink:href="#icon" x="0" y="0" fill="#447e9b"/>
|
||||||
<use xlink:href="#icon" x="0" y="1792" fill="#003366" />
|
<use xlink:href="#icon" x="0" y="512" fill="#003366" />
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 677 B After Width: | Height: | Size: 805 B |
9
app/static/admin/img/icon-debug-dark.svg
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc. -->
|
||||||
|
<!--
|
||||||
|
Icon Name: bug
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#bfbfbf" d="M256 0c53 0 96 43 96 96l0 3.6c0 15.7-12.7 28.4-28.4 28.4l-135.1 0c-15.7 0-28.4-12.7-28.4-28.4l0-3.6c0-53 43-96 96-96zM41.4 105.4c12.5-12.5 32.8-12.5 45.3 0l64 64c.7 .7 1.3 1.4 1.9 2.1c14.2-7.3 30.4-11.4 47.5-11.4l112 0c17.1 0 33.2 4.1 47.5 11.4c.6-.7 1.2-1.4 1.9-2.1l64-64c12.5-12.5 32.8-12.5 45.3 0s12.5 32.8 0 45.3l-64 64c-.7 .7-1.4 1.3-2.1 1.9c6.2 12 10.1 25.3 11.1 39.5l64.3 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-64 0c0 24.6-5.5 47.8-15.4 68.6c2.2 1.3 4.2 2.9 6 4.8l64 64c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0l-63.1-63.1c-24.5 21.8-55.8 36.2-90.3 39.6L272 240c0-8.8-7.2-16-16-16s-16 7.2-16 16l0 239.2c-34.5-3.4-65.8-17.8-90.3-39.6L86.6 502.6c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3l64-64c1.9-1.9 3.9-3.4 6-4.8C101.5 367.8 96 344.6 96 320l-64 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l64.3 0c1.1-14.1 5-27.5 11.1-39.5c-.7-.6-1.4-1.2-2.1-1.9l-64-64c-12.5-12.5-12.5-32.8 0-45.3z" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
9
app/static/admin/img/icon-debug.svg
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc. -->
|
||||||
|
<!--
|
||||||
|
Icon Name: bug
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#808080" d="M256 0c53 0 96 43 96 96l0 3.6c0 15.7-12.7 28.4-28.4 28.4l-135.1 0c-15.7 0-28.4-12.7-28.4-28.4l0-3.6c0-53 43-96 96-96zM41.4 105.4c12.5-12.5 32.8-12.5 45.3 0l64 64c.7 .7 1.3 1.4 1.9 2.1c14.2-7.3 30.4-11.4 47.5-11.4l112 0c17.1 0 33.2 4.1 47.5 11.4c.6-.7 1.2-1.4 1.9-2.1l64-64c12.5-12.5 32.8-12.5 45.3 0s12.5 32.8 0 45.3l-64 64c-.7 .7-1.4 1.3-2.1 1.9c6.2 12 10.1 25.3 11.1 39.5l64.3 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-64 0c0 24.6-5.5 47.8-15.4 68.6c2.2 1.3 4.2 2.9 6 4.8l64 64c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0l-63.1-63.1c-24.5 21.8-55.8 36.2-90.3 39.6L272 240c0-8.8-7.2-16-16-16s-16 7.2-16 16l0 239.2c-34.5-3.4-65.8-17.8-90.3-39.6L86.6 502.6c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3l64-64c1.9-1.9 3.9-3.4 6-4.8C101.5 367.8 96 344.6 96 320l-64 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l64.3 0c1.1-14.1 5-27.5 11.1-39.5c-.7-.6-1.4-1.2-2.1-1.9l-64-64c-12.5-12.5-12.5-32.8 0-45.3z" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -1,3 +1,11 @@
|
|||||||
<svg width="14" height="14" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="14" height="14" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512">
|
||||||
<path fill="#dd4646" d="M1490 1322q0 40-28 68l-136 136q-28 28-68 28t-68-28l-294-294-294 294q-28 28-68 28t-68-28l-136-136q-28-28-28-68t28-68l294-294-294-294q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 294 294-294q28-28 68-28t68 28l136 136q28 28 28 68t-28 68l-294 294 294 294q28 28 28 68z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<g>
|
||||||
|
<!--
|
||||||
|
Icon Name: xmark
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#dd4646" stroke="#dd4646" d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/>
|
||||||
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 392 B After Width: | Height: | Size: 689 B |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512">
|
||||||
<path fill="#2b70bf" d="m555 1335 78-141q-87-63-136-159t-49-203q0-121 61-225-229 117-381 353 167 258 427 375zm389-759q0-20-14-34t-34-14q-125 0-214.5 89.5T592 832q0 20 14 34t34 14 34-14 14-34q0-86 61-147t147-61q20 0 34-14t14-34zm363-191q0 7-1 9-105 188-315 566t-316 567l-49 89q-10 16-28 16-12 0-134-70-16-10-16-28 0-12 44-87-143-65-263.5-173T20 1029Q0 998 0 960t20-69q153-235 380-371t496-136q89 0 180 17l54-97q10-16 28-16 5 0 18 6t31 15.5 33 18.5 31.5 18.5T1291 358q16 10 16 27zm37 447q0 139-79 253.5T1056 1250l280-502q8 45 8 84zm448 128q0 35-20 69-39 64-109 145-150 172-347.5 267T896 1536l74-132q212-18 392.5-137T1664 960q-115-179-282-294l63-112q95 64 182.5 153T1772 891q20 34 20 69z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: eye-slash
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#2b70bf" d="M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c8.4-19.3 10.6-41.4 4.8-63.3c-11.1-41.5-47.8-69.4-88.6-71.1c-5.8-.2-9.2 6.1-7.4 11.7c2.1 6.4 3.3 13.2 3.3 20.3c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zM373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5L373 389.9z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 784 B After Width: | Height: | Size: 1.1 KiB |
9
app/static/admin/img/icon-info-dark.svg
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc. -->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-info
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#63b4eb" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336l24 0 0-64-24 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l48 0c13.3 0 24 10.7 24 24l0 88 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 630 B |
9
app/static/admin/img/icon-info.svg
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc. -->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-info
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#3f8cc1" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336l24 0 0-64-24 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l48 0c13.3 0 24 10.7 24 24l0 88 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 630 B |
9
app/static/admin/img/icon-no-dark.svg
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-xmark
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#f15f5f" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 645 B |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
<path fill="#dd4646" d="M1277 1122q0-26-19-45l-181-181 181-181q19-19 19-45 0-27-19-46l-90-90q-19-19-46-19-26 0-45 19l-181 181-181-181q-19-19-45-19-27 0-46 19l-90 90q-19 19-19 46 0 26 19 45l181 181-181 181q-19 19-19 45 0 27 19 46l90 90q19 19 46 19 26 0 45-19l181-181 181 181q19 19 45 19 27 0 46-19l90-90q19-19 19-46zm387-226q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-xmark
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#c63d3d" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 560 B After Width: | Height: | Size: 645 B |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
<path fill="#ffffff" d="M1024 1376v-192q0-14-9-23t-23-9h-192q-14 0-23 9t-9 23v192q0 14 9 23t23 9h192q14 0 23-9t9-23zm256-672q0-88-55.5-163t-138.5-116-170-41q-243 0-371 213-15 24 8 42l132 100q7 6 19 6 16 0 25-12 53-68 86-92 34-24 86-24 48 0 85.5 26t37.5 59q0 38-20 61t-68 45q-63 28-115.5 86.5t-52.5 125.5v36q0 14 9 23t23 9h192q14 0 23-9t9-23q0-19 21.5-49.5t54.5-49.5q32-18 49-28.5t46-35 44.5-48 28-60.5 12.5-81zm384 192q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-question
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#ffffff" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM169.8 165.3c7.9-22.3 29.1-37.3 52.8-37.3l58.3 0c34.9 0 63.1 28.3 63.1 63.1c0 22.6-12.1 43.5-31.7 54.8L280 264.4c-.2 13-10.9 23.6-24 23.6c-13.3 0-24-10.7-24-24l0-13.5c0-8.6 4.6-16.5 12.1-20.8l44.3-25.4c4.7-2.7 7.6-7.7 7.6-13.1c0-8.4-6.8-15.1-15.1-15.1l-58.3 0c-3.4 0-6.4 2.1-7.5 5.3l-.4 1.2c-4.4 12.5-18.2 19-30.6 14.6s-19-18.2-14.6-30.6l.4-1.2zM224 352a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 655 B After Width: | Height: | Size: 806 B |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
<path fill="#666666" d="M1024 1376v-192q0-14-9-23t-23-9h-192q-14 0-23 9t-9 23v192q0 14 9 23t23 9h192q14 0 23-9t9-23zm256-672q0-88-55.5-163t-138.5-116-170-41q-243 0-371 213-15 24 8 42l132 100q7 6 19 6 16 0 25-12 53-68 86-92 34-24 86-24 48 0 85.5 26t37.5 59q0 38-20 61t-68 45q-63 28-115.5 86.5t-52.5 125.5v36q0 14 9 23t23 9h192q14 0 23-9t9-23q0-19 21.5-49.5t54.5-49.5q32-18 49-28.5t46-35 44.5-48 28-60.5 12.5-81zm384 192q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-question
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#666666" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM169.8 165.3c7.9-22.3 29.1-37.3 52.8-37.3l58.3 0c34.9 0 63.1 28.3 63.1 63.1c0 22.6-12.1 43.5-31.7 54.8L280 264.4c-.2 13-10.9 23.6-24 23.6c-13.3 0-24-10.7-24-24l0-13.5c0-8.6 4.6-16.5 12.1-20.8l44.3-25.4c4.7-2.7 7.6-7.7 7.6-13.1c0-8.4-6.8-15.1-15.1-15.1l-58.3 0c-3.4 0-6.4 2.1-7.5 5.3l-.4 1.2c-4.4 12.5-18.2 19-30.6 14.6s-19-18.2-14.6-30.6l.4-1.2zM224 352a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 655 B After Width: | Height: | Size: 806 B |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
|
||||||
<path fill="#2b70bf" d="M1664 960q-152-236-381-353 61 104 61 225 0 185-131.5 316.5t-316.5 131.5-316.5-131.5-131.5-316.5q0-121 61-225-229 117-381 353 133 205 333.5 326.5t434.5 121.5 434.5-121.5 333.5-326.5zm-720-384q0-20-14-34t-34-14q-125 0-214.5 89.5t-89.5 214.5q0 20 14 34t34 14 34-14 14-34q0-86 61-147t147-61q20 0 34-14t14-34zm848 384q0 34-20 69-140 230-376.5 368.5t-499.5 138.5-499.5-139-376.5-368q-20-35-20-69t20-69q140-229 376.5-368t499.5-139 499.5 139 376.5 368q20 35 20 69z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: eye
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#2b70bf" d="M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM144 256a144 144 0 1 1 288 0 144 144 0 1 1 -288 0zm144-64c0 35.3-28.7 64-64 64c-7.1 0-13.9-1.2-20.3-3.3c-5.5-1.8-11.9 1.6-11.7 7.4c.3 6.9 1.3 13.8 3.2 20.7c13.7 51.2 66.4 81.6 117.6 67.9s81.6-66.4 67.9-117.6c-11.1-41.5-47.8-69.4-88.6-71.1c-5.8-.2-9.2 6.1-7.4 11.7c2.1 6.4 3.3 13.2 3.3 20.3z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 581 B After Width: | Height: | Size: 928 B |
9
app/static/admin/img/icon-yes-dark.svg
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-check
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#73c12f" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 558 B |
@@ -1,3 +1,9 @@
|
|||||||
<svg width="13" height="13" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
|
<svg width="13" height="13" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
<path fill="#70bf2b" d="M1412 734q0-28-18-46l-91-90q-19-19-45-19t-45 19l-408 407-226-226q-19-19-45-19t-45 19l-91 90q-18 18-18 46 0 27 18 45l362 362q19 19 45 19 27 0 46-19l543-543q18-18 18-45zm252 162q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z"/>
|
<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
|
||||||
|
<!--
|
||||||
|
Icon Name: circle-check
|
||||||
|
Icon Family: classic
|
||||||
|
Icon Style: solid
|
||||||
|
-->
|
||||||
|
<path fill="#649c35" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 436 B After Width: | Height: | Size: 558 B |