Compare commits

..

11 Commits

Author SHA1 Message Date
herel 0dac1a5505 build: optimize Docker image with multi-stage build and security improvements
- Implement multi-stage build to reduce final image size
- Install only production dependencies with npm ci --only=production
- Clean npm cache to reduce image size
- Improve layer caching by copying package files before application code
- Update package version from 1.0.0 to 1.0.1
2025-10-09 10:11:38 +02:00
herel 271eb107a2 feat: add OpenAPI documentation and comprehensive test suite
- Add OpenAPI schema endpoint at /openapi.json with proper logging
- Make server exportable for testing by wrapping app.listen in module check
- Add Jest test suite covering all API endpoints
- Improve request logging with IP addresses and timestamps
- Add development dependencies for testing (jest, supertest)
2025-09-02 12:26:30 +02:00
herel 69c216a0d0 chore: add node_modules to .gitignore 2025-09-02 12:23:36 +02:00
herel 3a4f58621a doc: add openapi.json 2025-09-02 10:31:59 +02:00
herel a63cf97638 chore: secure deploy 2025-09-02 10:30:08 +02:00
herel 6f452a2c93 🟢 deploy/netpol.yaml
🛠️ README.md -> updated local mods
🛠️ deploy/kustomization.yaml -> added netpol
2025-05-02 17:07:46 +02:00
herel 1f3f6a35e4 🛠️ deploy.yaml -> Security updates
added restrictions
2025-05-02 16:53:48 +02:00
herel 2c03527d00 add doc 2025-05-02 16:48:27 +02:00
herel 48ef406428 🛠️ index.js -> updated endpoint path 2025-05-02 16:45:08 +02:00
herel ad43004e46 🛠️ Dockerfile -> Node version updated 2025-05-02 16:44:58 +02:00
herel c6d693dc3a 🛠️ README.md -> Added fork info 2025-05-02 16:44:46 +02:00
16 changed files with 5895 additions and 16 deletions
+1
View File
@@ -0,0 +1 @@
node_modules/
+16 -9
View File
@@ -1,15 +1,22 @@
FROM node@sha256:86703151a18fcd06258e013073508c4afea8e19cd7ed451554221dd00aea83fc
FROM node:24-slim AS builder
WORKDIR /usr/src/app
# Copy dependency files first
COPY package*.json ./
# Install production dependencies only
RUN npm ci --only=production && npm cache clean --force
FROM node:24-slim
WORKDIR /usr/src/app
COPY --from=builder /usr/src/app/node_modules ./node_modules
# Copy application code
COPY . .
EXPOSE 3000
COPY package.json /usr/src/app/package.json
RUN npm install
USER node
COPY . /usr/src/app/
CMD ["npm", "start"]
+13
View File
@@ -1,5 +1,18 @@
# ❌ No-as-a-Service
FORKED FROM https://github.com/hotheadhacker/no-as-a-service
## local modifications
- answer on / instead of /no
- add /health endpoint for kube readiness probe
- add Dockerfile to build this sh*t
- kustomization in [deploy](deploy) directory (use your own registry)
the deploy runs non root, no caps, read only file system, network policy and sh*t ftw
## intro
<p align="center">
<img src="https://raw.githubusercontent.com/hotheadhacker/no-as-a-service/main/assets/imgs/naas-with-no-logo-bunny.png" width="800" alt="No-as-a-Service Banner" width="70%"/>
</p>
+62
View File
@@ -0,0 +1,62 @@
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
app: noaas
name: noaas
spec:
replicas: 2
selector:
matchLabels:
app: noaas
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
app: noaas
spec:
securityContext:
runAsUser: 1000
runAsGroup: 1000
runAsNonRoot: true
fsGroup: 2000
seccompProfile:
type: RuntimeDefault
automountServiceAccountToken: false
terminationGracePeriodSeconds: 3
containers:
- image: noaas
imagePullPolicy: IfNotPresent
name: noaas
ports:
- containerPort: 3000
name: http
readinessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 15
periodSeconds: 20
resources:
limits:
cpu: 1
memory: 128Mi
requests:
cpu: 10m
memory: 50Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- all
privileged: false
readOnlyRootFilesystem: true
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: noaas
+23
View File
@@ -0,0 +1,23 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
creationTimestamp: null
name: noaas
spec:
rules:
- host: no.parano.ch
http:
paths:
- backend:
service:
name: noaas
port:
name: http
path: /
pathType: Prefix
tls:
- hosts:
- no.parano.ch
secretName: noaas-tls
+14
View File
@@ -0,0 +1,14 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: noaas
resources:
- namespace.yaml
- deploy.yaml
- service.yaml
- ingress.yaml
- netpol.yaml
- pdb.yaml
images:
- name: noaas
newName: <my-harbor-url>/library/no-as-a-service
newTag: v0.0.5
+7
View File
@@ -0,0 +1,7 @@
apiVersion: v1
kind: Namespace
metadata:
creationTimestamp: null
name: noaas
spec: {}
status: {}
+19
View File
@@ -0,0 +1,19 @@
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: noaas
spec:
policyTypes:
- Ingress
- Egress
podSelector:
matchLabels:
app: noaas
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ingress-nginx
ports:
- protocol: TCP
port: 3000
+9
View File
@@ -0,0 +1,9 @@
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: noaas-pdb
spec:
minAvailable: 1
selector:
matchLabels:
app: noaas
+16
View File
@@ -0,0 +1,16 @@
apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
app: noaas
name: noaas
spec:
ports:
- name: http
port: 80
protocol: TCP
targetPort: http
selector:
app: noaas
type: ClusterIP
+26 -5
View File
@@ -9,6 +9,9 @@ const PORT = process.env.PORT || 3000;
// Load reasons from JSON
const reasons = JSON.parse(fs.readFileSync('./reasons.json', 'utf-8'));
// Load OpenAPI schema
const openapiSchema = JSON.parse(fs.readFileSync('./openapi.json', 'utf-8'));
// Rate limiter: 120 requests per minute per IP
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
@@ -21,17 +24,35 @@ const limiter = rateLimit({
app.use(limiter);
// Serve OpenAPI schema
app.get('/openapi.json', (req, res) => {
const ip = req.headers['x-forwarded-for'] || req.ip;
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] OpenAPI schema request from IP: ${ip}`);
res.json(openapiSchema);
});
// Random rejection reason endpoint
app.get('/no', (req, res) => {
app.get('/', (req, res) => {
const ip = req.headers['x-forwarded-for'] || req.ip;
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] Request from IP: ${ip}`);
const reason = reasons[Math.floor(Math.random() * reasons.length)];
res.json({ reason });
});
app.get('/health', (req, res) => {
const ip = req.headers['x-forwarded-for'] || req.ip;
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] Request from IP: ${ip}`);
res.json({"status": "ok"});
});
// Start server
app.listen(PORT, () => {
console.log(`No-as-a-Service is running on port ${PORT}`);
});
// Start server only if this file is run directly
if (require.main === module) {
app.listen(PORT, () => {
console.log(`No-as-a-Service is running on port ${PORT}`);
});
}
module.exports = app;
+115
View File
@@ -0,0 +1,115 @@
{
"openapi": "3.0.3",
"info": {
"title": "No-as-a-Service API",
"description": "A lightweight API that returns random rejection or \"no\" reasons. Perfect for any scenario: personal, professional, student life, dev life, or just because.",
"version": "1.0.0",
"contact": {
"name": "herel",
"url": "https://gitea.parano.ch/herel/no-as-a-service"
}
},
"servers": [
{
"url": "https://no.parano.ch",
"description": "Production server"
}
],
"paths": {
"/": {
"get": {
"summary": "Get a random rejection reason",
"description": "Returns a randomly selected excuse or rejection reason from a collection of 1000+ universal \"no\" responses.",
"operationId": "getRandomReason",
"responses": {
"200": {
"description": "Successful response with a random rejection reason",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ReasonResponse"
}
}
}
},
"429": {
"description": "Rate limit exceeded",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
}
}
}
},
"/health": {
"get": {
"summary": "Health check endpoint",
"description": "Returns the health status of the service for Kubernetes readiness probes.",
"operationId": "getHealth",
"responses": {
"200": {
"description": "Service is healthy",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HealthResponse"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"ReasonResponse": {
"type": "object",
"properties": {
"reason": {
"type": "string",
"description": "A randomly selected rejection reason",
"example": "This feels like something Future Me would yell at Present Me for agreeing to."
}
},
"required": ["reason"]
},
"HealthResponse": {
"type": "object",
"properties": {
"status": {
"type": "string",
"description": "Health status of the service",
"example": "ok"
}
},
"required": ["status"]
},
"ErrorResponse": {
"type": "object",
"properties": {
"error": {
"type": "string",
"description": "Error message",
"example": "Too many requests, please try again later. (120 reqs/min/IP)"
}
},
"required": ["error"]
}
}
},
"tags": [
{
"name": "Reasons",
"description": "Endpoints for getting random rejection reasons"
},
{
"name": "Health",
"description": "Health check endpoints"
}
]
}
+5516
View File
File diff suppressed because it is too large Load Diff
+7 -2
View File
@@ -1,15 +1,20 @@
{
"name": "no-as-service",
"version": "1.0.0",
"version": "1.0.1",
"description": "A lightweight API that returns random rejection or no reasons.",
"main": "index.js",
"scripts": {
"start": "node index.js"
"start": "node index.js",
"test": "jest"
},
"author": "hotheadhacker",
"license": "MIT",
"dependencies": {
"express": "^4.18.2",
"express-rate-limit": "^7.0.0"
},
"devDependencies": {
"jest": "^30.1.2",
"supertest": "^7.1.4"
}
}
+28
View File
@@ -0,0 +1,28 @@
const request = require('supertest');
describe('API Endpoints', () => {
let app;
beforeAll(() => {
app = require('../index.js');
});
test('should return a random reason at root endpoint', async () => {
const response = await request(app)
.get('/')
.expect(200)
.expect('Content-Type', /application\/json/);
expect(response.body).toHaveProperty('reason');
expect(typeof response.body.reason).toBe('string');
});
test('should return health status at /health endpoint', async () => {
const response = await request(app)
.get('/health')
.expect(200)
.expect('Content-Type', /application\/json/);
expect(response.body).toEqual({ status: 'ok' });
});
});
+23
View File
@@ -0,0 +1,23 @@
const request = require('supertest');
const fs = require('fs');
describe('OpenAPI Schema Endpoint', () => {
let app;
beforeAll(() => {
// Import the app after modifications
app = require('../index.js');
});
test('should serve OpenAPI schema at /openapi.json', async () => {
// Read the expected schema from the file
const expectedSchema = JSON.parse(fs.readFileSync('./openapi.json', 'utf-8'));
const response = await request(app)
.get('/openapi.json')
.expect(200)
.expect('Content-Type', /application\/json/);
expect(response.body).toEqual(expectedSchema);
});
});