Compare commits

..

15 Commits

Author SHA1 Message Date
Jonathan Miller d300cde639 feat(metrics): add active users, actions queue/running to Prometheus (#42)
Branch Policy Check / Verify merge target (pull_request) Successful in 1s
Extend the existing /metrics endpoint with 3 new application metrics:
- gitea_active_users_30d: users active in last 30 days
- gitea_actions_queue_length: pending action jobs
- gitea_actions_running_jobs: currently running jobs

No new dependencies — extends existing collector and statistic model.

Closes #42

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-19 21:44:37 -05:00
Jonathan Miller 5d84da9ae8 feat(ci): deploy workflow pushes Docker images to container registry
Updated deploy workflow:
- Builds image, pushes to git.mokoconsulting.tech container registry
- Supports dev and production environments via input selector
- Tags: v1.26.1-moko.N (production) or v1.26.1-moko.N-dev (dev)
- Always pushes :latest alongside versioned tag
- Images pullable from any machine via docker pull

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-19 21:18:16 -05:00
Jonathan Miller a8a01ed978 Merge branch 'dev' 2026-05-19 20:32:22 -05:00
Jonathan Miller 871883ef11 fix: add FastCryptoRandomHex/Bytes used by ScriptImport CSP nonces
Add ChaCha8-based fast crypto random functions required by the
TemplateContext.CspScriptNonce() method for Content-Security-Policy
nonce generation. ~20x faster than crypto/rand for session IDs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-19 20:07:27 -05:00
jmiller b441b0a350 chore: add issue templates [skip ci] 2026-05-20 00:37:37 +00:00
jmiller fcbc28735e chore: add issue templates [skip ci] 2026-05-20 00:37:31 +00:00
jmiller 5c3a36a225 chore: add issue templates [skip ci] 2026-05-20 00:37:25 +00:00
jmiller 8936883a40 chore: add issue templates [skip ci] 2026-05-20 00:37:19 +00:00
jmiller c3af273401 chore: add issue templates [skip ci] 2026-05-20 00:37:14 +00:00
jmiller 77f3a522eb chore: add issue templates [skip ci] 2026-05-20 00:37:08 +00:00
jmiller de2a2c9013 chore: add issue templates [skip ci] 2026-05-20 00:37:03 +00:00
jmiller a78e610040 chore: add issue templates [skip ci] 2026-05-20 00:36:58 +00:00
jmiller 707eec0098 chore: add issue templates [skip ci] 2026-05-20 00:36:53 +00:00
jmiller 8c89a33ecf Merge pull request 'feat(branding): replace all Gitea logos with Moko Consulting branding' (#124) from feat/custom-logo into main 2026-05-20 00:36:17 +00:00
Jonathan Miller c74a0d27e4 fix: restore full TemplateContext with ScriptImport, CspNonce methods
Restore context_template.go from commit 82bfde2a37 which added:
- ScriptImport() — generates script tags with CSP nonces
- CspScriptNonce() — generates per-request nonces
- HeadMetaContentSecurityPolicy() — CSP meta header
- CurrentWebBanner() — web banner support
- globalVars — cached script import configuration

These methods were missing from our manual TemplateContext definition,
causing "ScriptImport is not a method" runtime template errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-19 15:44:51 -05:00
14 changed files with 787 additions and 31 deletions
+110
View File
@@ -0,0 +1,110 @@
---
name: Architecture Decision Record (ADR)
about: Propose or document an architectural decision
title: '[ADR] '
labels: 'architecture, decision'
assignees: ''
---
## ADR Number
ADR-XXXX
## Status
- [ ] Proposed
- [ ] Accepted
- [ ] Deprecated
- [ ] Superseded by ADR-XXXX
## Context
Describe the issue or problem that motivates this decision.
## Decision
State the architecture decision and provide rationale.
## Consequences
### Positive
- List positive consequences
### Negative
- List negative consequences or trade-offs
### Neutral
- List neutral aspects
## Alternatives Considered
### Alternative 1
- Description
- Pros
- Cons
- Why not chosen
### Alternative 2
- Description
- Pros
- Cons
- Why not chosen
## Implementation Plan
1. Step 1
2. Step 2
3. Step 3
## Stakeholders
- **Decision Makers**: @user1, @user2
- **Consulted**: @user3, @user4
- **Informed**: team-name
## Technical Details
### Architecture Diagram
```
[Add diagram or link]
```
### Dependencies
- Dependency 1
- Dependency 2
### Impact Analysis
- **Performance**: [Impact description]
- **Security**: [Impact description]
- **Scalability**: [Impact description]
- **Maintainability**: [Impact description]
## Testing Strategy
- [ ] Unit tests
- [ ] Integration tests
- [ ] Performance tests
- [ ] Security tests
## Documentation
- [ ] Architecture documentation updated
- [ ] API documentation updated
- [ ] Developer guide updated
- [ ] Runbook created
## Migration Path
Describe how to migrate from current state to new architecture.
## Rollback Plan
Describe how to rollback if issues occur.
## Timeline
- **Proposal Date**:
- **Decision Date**:
- **Implementation Start**:
- **Expected Completion**:
## References
- Related ADRs:
- External resources:
- RFCs:
## Review Checklist
- [ ] Aligns with enterprise architecture principles
- [ ] Security implications reviewed
- [ ] Performance implications reviewed
- [ ] Cost implications reviewed
- [ ] Compliance requirements met
- [ ] Team consensus achieved
+48
View File
@@ -0,0 +1,48 @@
---
name: Bug Report
about: Report a bug or issue with the project
title: '[BUG] '
labels: 'bug'
assignees: ''
---
## Bug Description
A clear and concise description of what the bug is.
## Steps to Reproduce
1. Go to '...'
2. Click on '...'
3. Scroll down to '...'
4. See error
## Expected Behavior
A clear and concise description of what you expected to happen.
## Actual Behavior
A clear and concise description of what actually happened.
## Screenshots
If applicable, add screenshots to help explain your problem.
## Environment
- **Project**: [e.g., MokoDoliTools, moko-cassiopeia]
- **Version**: [e.g., 1.2.3]
- **Platform**: [e.g., Dolibarr 18.0, Joomla 5.0]
- **PHP Version**: [e.g., 8.1]
- **Database**: [e.g., MySQL 8.0, PostgreSQL 14]
- **Browser** (if applicable): [e.g., Chrome 120, Firefox 121]
- **OS**: [e.g., Ubuntu 22.04, Windows 11]
## Additional Context
Add any other context about the problem here.
## Possible Solution
If you have suggestions on how to fix the issue, please describe them here.
## Checklist
- [ ] I have searched for similar issues before creating this one
- [ ] I have provided all the requested information
- [ ] I have tested this on the latest stable version
- [ ] I have checked the documentation and couldn't find a solution
+18
View File
@@ -0,0 +1,18 @@
---
blank_issues_enabled: true
contact_links:
- name: 💼 Enterprise Support
url: https://mokoconsulting.tech/enterprise
about: Enterprise-level support and consultation services
- name: 💬 Ask a Question
url: https://mokoconsulting.tech/
about: Get help or ask questions through our website
- name: 📚 MokoStandards Documentation
url: https://git.mokoconsulting.tech/MokoConsulting/moko-platform
about: View our coding standards and best practices
- name: 🔒 Report a Security Vulnerability
url: https://git.mokoconsulting.tech/mokoconsulting-tech/.github-private/security/advisories/new
about: Report security vulnerabilities privately (for critical issues)
- name: 💡 Community Discussions
url: https://github.com/orgs/mokoconsulting-tech/discussions
about: Join community discussions and Q&A
+52
View File
@@ -0,0 +1,52 @@
---
name: Documentation Issue
about: Report an issue with documentation
title: '[DOCS] '
labels: 'documentation'
assignees: ''
---
## Documentation Issue
**Location**:
<!-- Specify the file, page, or section with the issue -->
## Issue Type
<!-- Mark the relevant option with an "x" -->
- [ ] Typo or grammar error
- [ ] Outdated information
- [ ] Missing documentation
- [ ] Unclear explanation
- [ ] Broken links
- [ ] Missing examples
- [ ] Other (specify below)
## Description
<!-- Clearly describe the documentation issue -->
## Current Content
<!-- Quote or describe the current documentation (if applicable) -->
```
Current text here
```
## Suggested Improvement
<!-- Provide your suggestion for how to improve the documentation -->
```
Suggested text here
```
## Additional Context
<!-- Add any other context, screenshots, or references -->
## Standards Alignment
- [ ] Follows MokoStandards documentation guidelines
- [ ] Uses en_US/en_GB localization
- [ ] Includes proper SPDX headers where applicable
## Checklist
- [ ] I have searched for similar documentation issues
- [ ] I have provided a clear description
- [ ] I have suggested an improvement (if applicable)
+51
View File
@@ -0,0 +1,51 @@
---
name: Feature Request
about: Suggest a new feature or enhancement
title: '[FEATURE] '
labels: 'enhancement'
assignees: ''
---
## Feature Description
A clear and concise description of the feature you'd like to see.
## Problem or Use Case
Describe the problem this feature would solve or the use case it addresses.
Ex. I'm always frustrated when [...]
## Proposed Solution
A clear and concise description of what you want to happen.
## Alternative Solutions
A clear and concise description of any alternative solutions or features you've considered.
## Benefits
Describe how this feature would benefit users:
- Who would use this feature?
- What problems does it solve?
- What value does it add?
## Implementation Details (Optional)
If you have ideas about how this could be implemented, share them here:
- Technical approach
- Files/components that might need changes
- Any concerns or challenges you foresee
## Additional Context
Add any other context, mockups, or screenshots about the feature request here.
## Relevant Standards
Does this relate to any standards in [MokoStandards](https://git.mokoconsulting.tech/MokoConsulting/MokoStandards)?
- [ ] Accessibility (WCAG 2.1 AA)
- [ ] Localization (en_US/en_GB)
- [ ] Security best practices
- [ ] Code quality standards
- [ ] Other: [specify]
## Checklist
- [ ] I have searched for similar feature requests before creating this one
- [ ] I have clearly described the use case and benefits
- [ ] I have considered alternative solutions
- [ ] This feature aligns with the project's goals and scope
+82
View File
@@ -0,0 +1,82 @@
---
name: Question
about: Ask a question about usage, features, or best practices
title: '[QUESTION] '
labels: ['question']
assignees: ['jmiller']
---
## Question
**Your question:**
## Context
**What are you trying to accomplish?**
**What have you already tried?**
**Category**:
- [ ] Script usage
- [ ] Configuration
- [ ] Workflow setup
- [ ] Documentation interpretation
- [ ] Best practices
- [ ] Integration
- [ ] Other: __________
## Environment (if relevant)
**Your setup**:
- Operating System:
- Version:
## What You've Researched
**Documentation reviewed**:
- [ ] README.md
- [ ] Project documentation
- [ ] Other (specify): __________
**Similar issues/questions found**:
- #
- #
## Expected Outcome
**What result are you hoping for?**
## Code/Configuration Samples
**Relevant code or configuration** (if applicable):
```bash
# Your code here
```
## Additional Context
**Any other relevant information:**
**Screenshots** (if helpful):
## Urgency
- [ ] Urgent (blocking work)
- [ ] Normal (can work on other things meanwhile)
- [ ] Low priority (just curious)
## Checklist
- [ ] I have searched existing issues and discussions
- [ ] I have reviewed relevant documentation
- [ ] I have provided sufficient context
- [ ] I have included code/configuration samples if relevant
- [ ] This is a genuine question (not a bug report or feature request)
+126
View File
@@ -0,0 +1,126 @@
---
name: Request for Comments (RFC)
about: Propose a significant change for community discussion
title: '[RFC] '
labels: 'rfc, discussion'
assignees: ''
---
## RFC Summary
One-paragraph summary of the proposal.
## Motivation
Why are we doing this? What use cases does it support? What is the expected outcome?
## Detailed Design
### Overview
Provide a detailed explanation of the proposed change.
### API Changes (if applicable)
```php
// Before
function oldApi($param1) { }
// After
function newApi($param1, $param2) { }
```
### User Experience Changes
Describe how users will interact with this change.
### Implementation Approach
High-level implementation strategy.
## Drawbacks
Why should we *not* do this?
## Alternatives
What other designs have been considered? What is the impact of not doing this?
### Alternative 1
- Description
- Trade-offs
### Alternative 2
- Description
- Trade-offs
## Adoption Strategy
How will existing users adopt this? Is this a breaking change?
### Migration Guide
```bash
# Steps to migrate
```
### Deprecation Timeline
- **Announcement**:
- **Deprecation**:
- **Removal**:
## Unresolved Questions
- Question 1
- Question 2
## Future Possibilities
What future work does this enable?
## Impact Assessment
### Performance
Expected performance impact.
### Security
Security considerations and implications.
### Compatibility
- **Backward Compatible**: [Yes / No]
- **Breaking Changes**: [List]
### Maintenance
Long-term maintenance considerations.
## Community Input
### Stakeholders
- [ ] Core team
- [ ] Module developers
- [ ] End users
- [ ] Enterprise customers
### Feedback Period
**Duration**: [e.g., 2 weeks]
**Deadline**: [date]
## Implementation Timeline
### Phase 1: Design
- [ ] RFC discussion
- [ ] Design finalization
- [ ] Approval
### Phase 2: Implementation
- [ ] Core implementation
- [ ] Tests
- [ ] Documentation
### Phase 3: Release
- [ ] Beta release
- [ ] Feedback collection
- [ ] Stable release
## Success Metrics
How will we measure success?
- Metric 1
- Metric 2
## References
- Related RFCs:
- External documentation:
- Prior art:
## Open Questions for Community
1. Question 1?
2. Question 2?
---
**Note**: This RFC is open for community discussion. Please provide feedback in the comments below.
+51
View File
@@ -0,0 +1,51 @@
---
name: Security Vulnerability Report
about: Report a security vulnerability (use only for non-critical issues)
title: '[SECURITY] '
labels: 'security'
assignees: ''
---
## ⚠️ IMPORTANT: Private Disclosure Required
**For critical security vulnerabilities, DO NOT use this template.**
Follow the process in [SECURITY.md](../SECURITY.md) for responsible disclosure.
Use this template only for:
- Security improvements
- Non-critical security suggestions
- Security documentation updates
---
## Security Issue
**Severity**:
<!-- Low, Medium, or informational only -->
## Description
<!-- Describe the security concern or improvement suggestion -->
## Affected Components
<!-- List the affected files, features, or components -->
## Suggested Mitigation
<!-- Describe how this could be addressed -->
## Standards Reference
Does this relate to security standards in [MokoStandards](https://git.mokoconsulting.tech/MokoConsulting/MokoStandards)?
- [ ] SPDX license identifiers
- [ ] Secret management
- [ ] Dependency security
- [ ] Access control
- [ ] Other: [specify]
## Additional Context
<!-- Add any other context about the security concern -->
## Checklist
- [ ] This is NOT a critical vulnerability requiring private disclosure
- [ ] I have reviewed the SECURITY.md policy
- [ ] I have provided sufficient detail for evaluation
+24
View File
@@ -0,0 +1,24 @@
---
name: Version Bump
about: Request or track a version change
title: '[VERSION] '
labels: 'version, type: version'
assignees: 'jmiller'
---
## Version Change
**Current version**: <!-- e.g., 01.02.03 -->
**Requested version**: <!-- e.g., 01.03.00 -->
**Change type**: <!-- patch / minor / major -->
## Reason
<!-- Why is this version bump needed? -->
## Checklist
- [ ] README.md `VERSION:` field updated
- [ ] CHANGELOG.md entry added
- [ ] Module descriptor version updated (Dolibarr: `$this->version`, Joomla: `<version>`)
- [ ] All file headers will be auto-propagated by `sync-version-on-merge` workflow
+60 -28
View File
@@ -1,6 +1,6 @@
# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
# SPDX-License-Identifier: GPL-3.0-or-later
# BRIEF: Build and deploy MokoGitea via SSH to production server
# BRIEF: Build MokoGitea Docker image, push to registry, and deploy
name: Deploy MokoGitea
@@ -8,9 +8,17 @@ on:
workflow_dispatch:
inputs:
version:
description: 'Version tag (e.g. v05.00.00)'
description: 'Version tag (e.g. v1.26.1-moko.2)'
required: true
default: 'latest'
environment:
description: 'Target environment'
required: true
default: 'dev'
type: choice
options:
- dev
- production
concurrency:
group: deploy-mokogitea
@@ -22,22 +30,39 @@ env:
DEPLOY_HOST: git.mokoconsulting.tech
DEPLOY_PORT: 2918
DEPLOY_USER: mokoconsulting
COMPOSE_DIR: /opt/gitea
SOURCE_DIR: /opt/gitea/source
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Determine version tag
id: version
- name: Determine settings
id: config
run: |
echo "tag=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT
VERSION="${{ github.event.inputs.version }}"
ENV="${{ github.event.inputs.environment }}"
- name: Deploy via SSH
if [ "$ENV" = "production" ]; then
echo "compose_dir=/opt/gitea" >> $GITHUB_OUTPUT
echo "container=mokogitea" >> $GITHUB_OUTPUT
echo "source_dir=/opt/gitea/source" >> $GITHUB_OUTPUT
echo "branch=main" >> $GITHUB_OUTPUT
echo "tag=${VERSION}" >> $GITHUB_OUTPUT
else
echo "compose_dir=/opt/gitea-dev" >> $GITHUB_OUTPUT
echo "container=mokogitea-dev" >> $GITHUB_OUTPUT
echo "source_dir=/opt/gitea-dev/source" >> $GITHUB_OUTPUT
echo "branch=dev" >> $GITHUB_OUTPUT
echo "tag=${VERSION}-dev" >> $GITHUB_OUTPUT
fi
- name: Build, push, and deploy via SSH
env:
SSH_PRIVATE_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
VERSION_TAG: ${{ steps.version.outputs.tag }}
TAG: ${{ steps.config.outputs.tag }}
BRANCH: ${{ steps.config.outputs.branch }}
SOURCE_DIR: ${{ steps.config.outputs.source_dir }}
COMPOSE_DIR: ${{ steps.config.outputs.compose_dir }}
CONTAINER: ${{ steps.config.outputs.container }}
run: |
mkdir -p ~/.ssh
echo "$SSH_PRIVATE_KEY" > ~/.ssh/deploy_key
@@ -47,56 +72,63 @@ jobs:
$SSH_CMD "echo 'SSH connected'"
# Clone or update source
# Pull latest source
$SSH_CMD "
set -e
if [ ! -d ${{ env.SOURCE_DIR }}/.git ]; then
git clone https://git.mokoconsulting.tech/MokoConsulting/MokoGitea.git ${{ env.SOURCE_DIR }}
if [ ! -d ${SOURCE_DIR}/.git ]; then
git clone -b ${BRANCH} https://git.mokoconsulting.tech/MokoConsulting/MokoGitea.git ${SOURCE_DIR}
fi
cd ${{ env.SOURCE_DIR }}
git fetch origin main
git reset --hard origin/main
cd ${SOURCE_DIR}
git fetch origin ${BRANCH}
git reset --hard origin/${BRANCH}
"
# Build Docker image on server (standard root layout, -p 1 for 12GB server)
# Build Docker image
$SSH_CMD "
set -e
cd ${{ env.SOURCE_DIR }}
docker build \
--build-arg GOFLAGS='-p 1' \
--tag ${{ env.REGISTRY }}/${{ env.IMAGE }}:${VERSION_TAG} \
cd ${SOURCE_DIR}
docker build --no-cache --build-arg GOFLAGS='-p 1' \
--tag ${{ env.REGISTRY }}/${{ env.IMAGE }}:${TAG} \
--tag ${{ env.REGISTRY }}/${{ env.IMAGE }}:latest \
-f Dockerfile .
"
# Push to container registry
$SSH_CMD "
set -e
docker push ${{ env.REGISTRY }}/${{ env.IMAGE }}:${TAG}
docker push ${{ env.REGISTRY }}/${{ env.IMAGE }}:latest
"
# Update compose and restart
$SSH_CMD "
set -e
cd ${{ env.COMPOSE_DIR }}
sed -i 's|${{ env.IMAGE }}:[^ ]*|${{ env.IMAGE }}:${VERSION_TAG}|' docker-compose.yml
docker compose up -d gitea
cd ${COMPOSE_DIR}
sed -i 's|${{ env.IMAGE }}:[^ ]*|${{ env.IMAGE }}:${TAG}|' docker-compose.yml
docker compose up -d ${CONTAINER}
"
# Health check
$SSH_CMD "
for i in 1 2 3 4 5 6 7 8; do
sleep 15
if docker inspect --format='{{.State.Health.Status}}' gitea 2>/dev/null | grep -q healthy; then
echo 'Gitea is healthy!'
if docker inspect --format='{{.State.Health.Status}}' ${CONTAINER} 2>/dev/null | grep -q healthy; then
echo 'Container healthy!'
docker inspect --format='Image: {{.Config.Image}}' ${CONTAINER}
exit 0
fi
echo \"Waiting... (attempt \$i/8)\"
done
echo 'Health check failed'
docker logs gitea --tail 20
docker logs ${CONTAINER} --tail 20
exit 1
"
- name: Verify
run: |
sleep 5
curl -sf https://git.mokoconsulting.tech/api/healthz && echo " — API healthy"
curl -sf https://${{ env.DEPLOY_HOST }}/api/healthz && echo " — API healthy"
- name: Notify on failure
if: failure()
run: echo "::error::Deploy failed for ${{ steps.version.outputs.tag }}"
run: echo "::error::Deploy failed for ${{ steps.config.outputs.tag }}"
+21
View File
@@ -6,6 +6,7 @@ package activities
import (
"context"
actions_model "code.gitea.io/gitea/models/actions"
asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
@@ -18,6 +19,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/models/webhook"
"code.gitea.io/gitea/modules/optional"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
)
@@ -37,6 +39,11 @@ type Statistic struct {
Branches, Tags, CommitStatus int64
IssueByLabel []IssueByLabelCount
IssueByRepository []IssueByRepositoryCount
// MokoGitea extended metrics
ActiveUsers30d int64
ActionsQueueLength int64
ActionsRunningJobs int64
}
}
@@ -131,5 +138,19 @@ func GetStatistic(ctx context.Context) (stats Statistic) {
stats.Counter.Attachment, _ = e.Count(new(repo_model.Attachment))
stats.Counter.Project, _ = e.Count(new(project_model.Project))
stats.Counter.ProjectColumn, _ = e.Count(new(project_model.Column))
// MokoGitea extended metrics
// Active users in last 30 days (users who performed any action)
stats.Counter.ActiveUsers30d, _ = e.Where("last_login_unix > ?",
timeutil.TimeStampNow()-30*24*60*60).Count(new(user_model.User))
// Actions queue and running jobs (if actions enabled)
if setting.Actions.Enabled {
stats.Counter.ActionsQueueLength, _ = e.Where("status = ?", 1). // StatusWaiting
Count(new(actions_model.ActionRunJob))
stats.Counter.ActionsRunningJobs, _ = e.Where("status = ?", 2). // StatusRunning
Count(new(actions_model.ActionRunJob))
}
return stats
}
+40
View File
@@ -46,6 +46,11 @@ type Collector struct {
Users *prometheus.Desc
Watches *prometheus.Desc
Webhooks *prometheus.Desc
// MokoGitea extended metrics
ActiveUsers30d *prometheus.Desc
ActionsQueueLength *prometheus.Desc
ActionsRunningJobs *prometheus.Desc
}
// NewCollector returns a new Collector with all prometheus.Desc initialized
@@ -196,6 +201,21 @@ func NewCollector() Collector {
"Number of Webhooks",
nil, nil,
),
ActiveUsers30d: prometheus.NewDesc(
namespace+"active_users_30d",
"Number of active users in the last 30 days",
nil, nil,
),
ActionsQueueLength: prometheus.NewDesc(
namespace+"actions_queue_length",
"Number of actions jobs waiting to run",
nil, nil,
),
ActionsRunningJobs: prometheus.NewDesc(
namespace+"actions_running_jobs",
"Number of actions jobs currently running",
nil, nil,
),
}
}
@@ -229,6 +249,9 @@ func (c Collector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.Users
ch <- c.Watches
ch <- c.Webhooks
ch <- c.ActiveUsers30d
ch <- c.ActionsQueueLength
ch <- c.ActionsRunningJobs
}
// Collect returns the metrics with values
@@ -392,4 +415,21 @@ func (c Collector) Collect(ch chan<- prometheus.Metric) {
prometheus.GaugeValue,
float64(stats.Counter.Webhook),
)
// MokoGitea extended metrics
ch <- prometheus.MustNewConstMetric(
c.ActiveUsers30d,
prometheus.GaugeValue,
float64(stats.Counter.ActiveUsers30d),
)
ch <- prometheus.MustNewConstMetric(
c.ActionsQueueLength,
prometheus.GaugeValue,
float64(stats.Counter.ActionsQueueLength),
)
ch <- prometheus.MustNewConstMetric(
c.ActionsRunningJobs,
prometheus.GaugeValue,
float64(stats.Counter.ActionsRunningJobs),
)
}
+29
View File
@@ -6,11 +6,14 @@ package util
import (
"bytes"
"crypto/rand"
"encoding/hex"
"fmt"
"math/big"
rand2 "math/rand/v2"
"slices"
"strconv"
"strings"
"sync"
"golang.org/x/text/cases"
"golang.org/x/text/language"
@@ -91,6 +94,32 @@ func CryptoRandomBytes(length int64) ([]byte, error) {
return buf, err
}
var chaCha8RandPool = sync.OnceValue(func() *sync.Pool {
return &sync.Pool{
New: func() any {
var buf [32]byte
_, _ = rand.Read(buf[:])
return rand2.NewChaCha8(buf)
},
}
})
// FastCryptoRandomBytes returns random bytes using ChaCha8 (~20x faster than crypto/rand).
func FastCryptoRandomBytes(length int) []byte {
pool := chaCha8RandPool()
chaCha8Rand := pool.Get().(*rand2.ChaCha8)
defer pool.Put(chaCha8Rand)
buf := make([]byte, length)
_, _ = chaCha8Rand.Read(buf)
return buf
}
// FastCryptoRandomHex returns a random hex string of the given length.
func FastCryptoRandomHex(length int) string {
buf := FastCryptoRandomBytes(length / 2)
return hex.EncodeToString(buf)
}
// ToLowerASCII returns s with all ASCII letters mapped to their lower case.
func ToLowerASCII(s string) string {
b := []byte(s)
+75 -3
View File
@@ -5,20 +5,23 @@ package context
import (
"context"
"fmt"
"html"
"html/template"
"net/http"
"strconv"
"strings"
"sync"
"time"
"code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/public"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web/middleware"
"code.gitea.io/gitea/services/webtheme"
)
// TemplateContext is a map that holds template rendering context data
// and implements context.Context for passing request-scoped values.
type TemplateContext map[string]any
var _ context.Context = TemplateContext(nil)
@@ -85,5 +88,74 @@ func (c TemplateContext) AppFullLink(link ...string) template.URL {
if len(link) == 0 {
return template.URL(s)
}
return template.URL(s + "/" + strings.TrimPrefix(link[0], "/"))
return template.URL(s + strings.TrimPrefix(link[0], "/"))
}
var globalVars = sync.OnceValue(func() (ret struct {
scriptImportRemainingPart string
},
) {
// add onerror handler to alert users when the script fails to load:
// * for end users: there were many users reporting that "UI doesn't work", actually they made mistakes in their config
// * for developers: help them to remember to run "make watch-frontend" to build frontend assets
// the message will be directly put in the onerror JS code's string
onScriptErrorPrompt := `Please make sure the asset files can be accessed.`
if !setting.IsProd {
onScriptErrorPrompt += `\n\nFor development, run: make watch-frontend.`
}
onScriptErrorJS := fmt.Sprintf(`alert('Failed to load asset file from ' + this.src + '. %s')`, onScriptErrorPrompt)
ret.scriptImportRemainingPart = `onerror="` + html.EscapeString(onScriptErrorJS) + `"></script>`
return ret
})
func (c TemplateContext) ScriptImport(path string, typ ...string) template.HTML {
if len(typ) > 0 {
if typ[0] == "module" {
return template.HTML(`<script nonce="` + c.CspScriptNonce() + `" type="module" src="` + html.EscapeString(public.AssetURI(path)) + `" ` + globalVars().scriptImportRemainingPart)
}
panic("unsupported script type: " + typ[0])
}
return template.HTML(`<script nonce="` + c.CspScriptNonce() + `" src="` + html.EscapeString(public.AssetURI(path)) + `" ` + globalVars().scriptImportRemainingPart)
}
func (c TemplateContext) CspScriptNonce() (ret string) {
// Generate a random nonce for each request and cache it in the context to make it usable during the whole rendering process.
//
// Some "<script>" tags are not in the CSP context, so they don't need nonce,
// these tags are written as "<script nonce>" to help developers to know that "no script nonce attribute is missing"
// (e.g.: when they grep the codebase for "script" tags)
ret, _ = c["_cspScriptNonce"].(string)
if ret == "" {
ret = util.FastCryptoRandomHex(32) // 16 bytes / 128 bits entropy
c["_cspScriptNonce"] = ret
}
return ret
}
func (c TemplateContext) HeadMetaContentSecurityPolicy() template.HTML {
// The CSP problem is more complicated than it looks.
// Gitea was designed to support various "customizations", including:
// * custom themes (custom CSS and JS)
// * custom assets URL (CDN)
// * custom plugins and external renders (e.g.: PlantUML render, and the renders might also load some JS/CSS assets)
// There is no easy way for end users to make the CSP "source" completely right.
//
// There can be 2 approaches in the future:
// A. Let end users to configure their reverse proxy to add CSP header
// * Browsers will merge and use the stricter rules between Gitea and reverse proxy
// B. Introduce some config options in "app.ini"
// * Maybe this approach should be avoided, don't make the config system too complex, just let users use A
return template.HTML(`<meta http-equiv="Content-Security-Policy" content="` +
// allow all by default (the same as old releases with no CSP)
// "data:" is used to load the manifest in head (maybe also need to be refactored in the future)
// maybe some images are also loaded by "data:", need to investigate
`default-src * data:;` +
// enforce nonce for all scripts, disallow inline scripts
`script-src * 'nonce-` + c.CspScriptNonce() + `';` +
// it seems that Vue needs the unsafe-inline, and our custom colors (e.g.: label) also need it
`style-src * 'unsafe-inline';` +
`">`)
}