diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ebb21f..5767480 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -126,6 +126,26 @@ jobs: file: deploy/Dockerfile tags: s3rius/rustus:latest,s3rius/rustus:${{env.APP_VERSION}} + release_helm: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Configure Git + run: | + git config user.name "$GITHUB_ACTOR" + git config user.email "$GITHUB_ACTOR@users.noreply.github.com" + - name: Install Helm + uses: azure/setup-helm@v1 + with: + version: v3.7.1 + - name: Run chart-releaser + uses: helm/chart-releaser-action@v1.3.0 + with: + charts_dir: ./deploy + env: + CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}" + publish_crate: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1e12134..b4063cb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -80,18 +80,14 @@ jobs: - uses: actions/checkout@v2 with: fetch-depth: 0 - - name: Install nightly toolchain - run: rustup toolchain install nightly --component llvm-tools-preview - - name: Install cargo-llvm-cov - uses: taiki-e/install-action@cargo-llvm-cov - - name: Generate code coverage - run: cargo llvm-cov --features=all,integration_tests --lcov --output-path lcov.info -- --test-threads 1 + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + - name: Run tests + run: cargo test --features=all,integration_tests -- --test-threads 1 env: TEST_REDIS_URL: redis://localhost:${{ job.services.redis.ports['6379'] }}/0 TEST_DB_URL: postgresql://rustus:rustus@localhost:${{ job.services.pg.ports['5432'] }}/rustus TEST_AMQP_URL: amqp://guest:guest@localhost:${{ job.services.rabbit.ports['5672'] }} - - name: Coveralls - uses: coverallsapp/github-action@master - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - path-to-lcov: lcov.info diff --git a/Cargo.lock b/Cargo.lock index 7a4aef8..6e31f9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1456,6 +1456,15 @@ dependencies = [ "opaque-debug 0.3.0", ] +[[package]] +name = "md-5" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" +dependencies = [ + "digest 0.10.3", +] + [[package]] name = "memchr" version = "2.4.1" @@ -2192,7 +2201,7 @@ dependencies = [ "itoa 0.4.8", "percent-encoding", "pin-project-lite", - "sha1", + "sha1 0.6.1", "tokio", "tokio-util 0.6.9", "url", @@ -2375,7 +2384,7 @@ dependencies = [ [[package]] name = "rustus" -version = "0.4.7" +version = "0.4.8" dependencies = [ "actix-files", "actix-rt", @@ -2385,12 +2394,14 @@ dependencies = [ "bytes", "chrono", "derive_more", + "digest 0.10.3", "fern", "futures", "httptest", "lapin", "lazy_static", "log", + "md-5 0.10.1", "mobc-lapin", "mobc-redis", "openssl", @@ -2399,6 +2410,8 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha1 0.10.1", + "sha2 0.10.2", "strfmt", "structopt", "strum", @@ -2590,6 +2603,17 @@ dependencies = [ "sha1_smol", ] +[[package]] +name = "sha1" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77f4e7f65455545c2153c1253d25056825e77ee2533f0e41deb65a93a34852f" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.3", +] + [[package]] name = "sha1_smol" version = "1.0.0" @@ -2609,6 +2633,17 @@ dependencies = [ "opaque-debug 0.3.0", ] +[[package]] +name = "sha2" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.3", +] + [[package]] name = "signal-hook-registry" version = "1.4.0" @@ -2711,7 +2746,7 @@ dependencies = [ "libc", "libsqlite3-sys", "log", - "md-5", + "md-5 0.9.1", "memchr", "num-bigint", "once_cell", @@ -2725,7 +2760,7 @@ dependencies = [ "serde", "serde_json", "sha-1 0.9.8", - "sha2", + "sha2 0.9.9", "smallvec", "sqlformat", "sqlx-rt", @@ -2799,7 +2834,7 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "sha1", + "sha1 0.6.1", "syn", ] diff --git a/Cargo.toml b/Cargo.toml index 7464294..33db9d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rustus" -version = "0.4.7" +version = "0.4.8" edition = "2021" description = "TUS protocol implementation written in Rust." keywords = [ @@ -31,6 +31,24 @@ thiserror = "^1.0" url = "^2.2.2" bytes = "^1.1.0" +[dependencies.digest] +version = "0.10.3" +optional = true + +[dependencies.sha1] +version = "^0.10.1" +features = ["compress"] +optional = true + +[dependencies.sha2] +version = "^0.10.1" +features = ["compress"] +optional = true + +[dependencies.md-5] +version = "^0.10.1" +optional = true + [dependencies.futures] version = "^0.3.21" @@ -108,12 +126,13 @@ features = ["v4"] version = "^1.0.0-alpha.1" [features] -all = ["redis_info_storage", "db_info_storage", "http_notifier", "amqp_notifier"] +all = ["redis_info_storage", "db_info_storage", "http_notifier", "amqp_notifier", "hashers"] amqp_notifier = ["lapin", "tokio-amqp", "mobc-lapin"] db_info_storage = ["rbatis", "rbson"] default = [] http_notifier = ["reqwest"] redis_info_storage = ["mobc-redis"] +hashers = ["md-5", "sha1", "sha2", "digest"] ### For testing test_redis = [] diff --git a/deploy/Dockerfile b/deploy/Dockerfile index 96c0cb4..4fca83a 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -14,6 +14,6 @@ COPY . . RUN cargo build --release --bin rustus --features=all FROM debian:bullseye-20211201-slim AS runtime -WORKDIR app +WORKDIR /app COPY --from=builder /app/target/release/rustus /usr/local/bin/ ENTRYPOINT ["/usr/local/bin/rustus"] diff --git a/deploy/alpine.Dockerfile b/deploy/alpine.Dockerfile index be8e4df..deb1275 100644 --- a/deploy/alpine.Dockerfile +++ b/deploy/alpine.Dockerfile @@ -7,5 +7,6 @@ ADD "https://github.com/s3rius/rustus/releases/download/${app_version}/rustus-${ RUN tar xvf *.tar.gz RUN rm *.tar.gz RUN mv rustus /bin +WORKDIR /app ENTRYPOINT ["/bin/rustus"] \ No newline at end of file diff --git a/deploy/helm/.helmignore b/deploy/helm/.helmignore new file mode 100644 index 0000000..0e8a0eb --- /dev/null +++ b/deploy/helm/.helmignore @@ -0,0 +1,23 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*.orig +*~ +# Various IDEs +.project +.idea/ +*.tmproj +.vscode/ diff --git a/deploy/helm/Chart.lock b/deploy/helm/Chart.lock new file mode 100644 index 0000000..188b0a7 --- /dev/null +++ b/deploy/helm/Chart.lock @@ -0,0 +1,12 @@ +dependencies: +- name: redis + repository: https://charts.bitnami.com/bitnami + version: 16.6.0 +- name: postgresql + repository: https://charts.bitnami.com/bitnami + version: 11.1.9 +- name: mysql + repository: https://charts.bitnami.com/bitnami + version: 8.8.27 +digest: sha256:96a4a257c98a0c8dbe07690d480dec99a1a73c5074e5e8811d6947e741eb9126 +generated: "2022-03-24T14:49:00.598734768+04:00" diff --git a/deploy/helm/Chart.yaml b/deploy/helm/Chart.yaml new file mode 100644 index 0000000..a39382b --- /dev/null +++ b/deploy/helm/Chart.yaml @@ -0,0 +1,40 @@ +apiVersion: v2 +name: rustus +description: A Helm chart for rustus +home: https://github.com/s3rius/rustus/ +icon: https://raw.githubusercontent.com/s3rius/rustus/master/imgs/logo.svg +# A chart can be either an 'application' or a 'library' chart. +# +# Application charts are a collection of templates that can be packaged into versioned archives +# to be deployed. +# +# Library charts provide useful utilities or functions for the chart developer. They're included as +# a dependency of application charts to inject those utilities and functions into the rendering +# pipeline. Library charts do not define any templates and therefore cannot be deployed. +type: application + +# This is the chart version. This version number should be incremented each time you make changes +# to the chart and its templates, including the app version. +# Versions are expected to follow Semantic Versioning (https://semver.org/) +version: 0.1.0 + +# This is the version number of the application being deployed. This version number should be +# incremented each time you make changes to the application. Versions are not expected to +# follow Semantic Versioning. They should reflect the version the application is using. +# It is recommended to use it with quotes. +appVersion: "0.4.8" + + +dependencies: + - name: redis + version: ^16.0 + condition: redis.enabled + repository: "https://charts.bitnami.com/bitnami" + - name: postgresql + version: ^11.0 + condition: postgresql.enabled + repository: "https://charts.bitnami.com/bitnami" + - name: mysql + version: ^8.0 + condition: mysql.enabled + repository: "https://charts.bitnami.com/bitnami" \ No newline at end of file diff --git a/deploy/helm/charts/mysql-8.8.27.tgz b/deploy/helm/charts/mysql-8.8.27.tgz new file mode 100644 index 0000000..91094de Binary files /dev/null and b/deploy/helm/charts/mysql-8.8.27.tgz differ diff --git a/deploy/helm/charts/postgresql-11.1.9.tgz b/deploy/helm/charts/postgresql-11.1.9.tgz new file mode 100644 index 0000000..e308ad4 Binary files /dev/null and b/deploy/helm/charts/postgresql-11.1.9.tgz differ diff --git a/deploy/helm/charts/redis-16.6.0.tgz b/deploy/helm/charts/redis-16.6.0.tgz new file mode 100644 index 0000000..770de4e Binary files /dev/null and b/deploy/helm/charts/redis-16.6.0.tgz differ diff --git a/deploy/helm/templates/NOTES.txt b/deploy/helm/templates/NOTES.txt new file mode 100644 index 0000000..216b570 --- /dev/null +++ b/deploy/helm/templates/NOTES.txt @@ -0,0 +1,22 @@ +1. Get the application URL by running these commands: +{{- if .Values.ingress.enabled }} +{{- range $host := .Values.ingress.hosts }} + {{- range .paths }} + http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }} + {{- end }} +{{- end }} +{{- else if contains "NodePort" .Values.service.type }} + export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "rustus.fullname" . }}) + export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") + echo http://$NODE_IP:$NODE_PORT +{{- else if contains "LoadBalancer" .Values.service.type }} + NOTE: It may take a few minutes for the LoadBalancer IP to be available. + You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "rustus.fullname" . }}' + export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "rustus.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}") + echo http://$SERVICE_IP:{{ .Values.service.port }} +{{- else if contains "ClusterIP" .Values.service.type }} + export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "rustus.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") + export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") + echo "Visit http://127.0.0.1:8080 to use your application" + kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT +{{- end }} diff --git a/deploy/helm/templates/_helpers.tpl b/deploy/helm/templates/_helpers.tpl new file mode 100644 index 0000000..218dbb7 --- /dev/null +++ b/deploy/helm/templates/_helpers.tpl @@ -0,0 +1,63 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "rustus.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "rustus.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "rustus.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "rustus.labels" -}} +helm.sh/chart: {{ include "rustus.chart" . }} +{{ include "rustus.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "rustus.selectorLabels" -}} +app: {{ include "rustus.name" . }} +app.kubernetes.io/name: {{ include "rustus.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "rustus.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "rustus.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} diff --git a/deploy/helm/templates/deployment.yaml b/deploy/helm/templates/deployment.yaml new file mode 100644 index 0000000..320d368 --- /dev/null +++ b/deploy/helm/templates/deployment.yaml @@ -0,0 +1,83 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "rustus.fullname" . }} + labels: + {{- include "rustus.labels" . | nindent 4 }} +spec: + {{- if not .Values.autoscaling.enabled }} + replicas: {{ .Values.replicaCount }} + {{- end }} + selector: + matchLabels: + {{- include "rustus.selectorLabels" . | nindent 6 }} + template: + metadata: + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + labels: + {{- include "rustus.selectorLabels" . | nindent 8 }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + serviceAccountName: {{ include "rustus.serviceAccountName" . }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: {{ .Chart.Name }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + {{- with .Values.image.command }} + command: + {{- . | toYaml | nindent 12 }} + {{- end }} + ports: + - name: http + containerPort: {{ default 1081 .Values.env.RUSTUS_PORT }} + protocol: TCP + readinessProbe: + httpGet: + path: /health + port: http + {{- with .Values.env }} + env: + {{- range $key, $val := . }} + - name: {{ $key | quote }} + value: {{ $val | quote }} + {{- end }} + {{- end }} + {{- if .Values.persistence.enabled }} + volumeMounts: + - name: data + mountPath: {{ default "/app/data" .Values.env.RUSTUS_DATA_DIR }} + {{- end }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- if .Values.persistence.enabled }} + volumes: + - name: data + persistentVolumeClaim: + {{- if .Values.persistence.existingClaim }} + claimName: {{ .Values.persistence.existingClaim }} + {{- else }} + claimName: {{ printf "rustus-data-%s" (include "rustus.fullname" .) }} + {{- end }} + {{- end }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/deploy/helm/templates/hpa.yaml b/deploy/helm/templates/hpa.yaml new file mode 100644 index 0000000..13d5fa1 --- /dev/null +++ b/deploy/helm/templates/hpa.yaml @@ -0,0 +1,28 @@ +{{- if .Values.autoscaling.enabled }} +apiVersion: autoscaling/v2beta1 +kind: HorizontalPodAutoscaler +metadata: + name: {{ include "rustus.fullname" . }} + labels: + {{- include "rustus.labels" . | nindent 4 }} +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{ include "rustus.fullname" . }} + minReplicas: {{ .Values.autoscaling.minReplicas }} + maxReplicas: {{ .Values.autoscaling.maxReplicas }} + metrics: + {{- if .Values.autoscaling.targetCPUUtilizationPercentage }} + - type: Resource + resource: + name: cpu + targetAverageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} + {{- end }} + {{- if .Values.autoscaling.targetMemoryUtilizationPercentage }} + - type: Resource + resource: + name: memory + targetAverageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }} + {{- end }} +{{- end }} diff --git a/deploy/helm/templates/ingress.yaml b/deploy/helm/templates/ingress.yaml new file mode 100644 index 0000000..9c17955 --- /dev/null +++ b/deploy/helm/templates/ingress.yaml @@ -0,0 +1,61 @@ +{{- if .Values.ingress.enabled -}} +{{- $fullName := include "rustus.fullname" . -}} +{{- $svcPort := .Values.service.port -}} +{{- if and .Values.ingress.className (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) }} + {{- if not (hasKey .Values.ingress.annotations "kubernetes.io/ingress.class") }} + {{- $_ := set .Values.ingress.annotations "kubernetes.io/ingress.class" .Values.ingress.className}} + {{- end }} +{{- end }} +{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}} +apiVersion: networking.k8s.io/v1 +{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}} +apiVersion: networking.k8s.io/v1beta1 +{{- else -}} +apiVersion: extensions/v1beta1 +{{- end }} +kind: Ingress +metadata: + name: {{ $fullName }} + labels: + {{- include "rustus.labels" . | nindent 4 }} + {{- with .Values.ingress.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- if and .Values.ingress.className (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) }} + ingressClassName: {{ .Values.ingress.className }} + {{- end }} + {{- if .Values.ingress.tls }} + tls: + {{- range .Values.ingress.tls }} + - hosts: + {{- range .hosts }} + - {{ . | quote }} + {{- end }} + secretName: {{ .secretName }} + {{- end }} + {{- end }} + rules: + {{- range .Values.ingress.hosts }} + - host: {{ .host | quote }} + http: + paths: + {{- range .paths }} + - path: {{ .path }} + {{- if and .pathType (semverCompare ">=1.18-0" $.Capabilities.KubeVersion.GitVersion) }} + pathType: {{ .pathType }} + {{- end }} + backend: + {{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }} + service: + name: {{ $fullName }} + port: + number: {{ $svcPort }} + {{- else }} + serviceName: {{ $fullName }} + servicePort: {{ $svcPort }} + {{- end }} + {{- end }} + {{- end }} +{{- end }} diff --git a/deploy/helm/templates/pvc.yml b/deploy/helm/templates/pvc.yml new file mode 100644 index 0000000..5836d74 --- /dev/null +++ b/deploy/helm/templates/pvc.yml @@ -0,0 +1,30 @@ +{{- if and (.Values.persistence.enabled) (not .Values.persistence.existingClaim) }} +kind: PersistentVolumeClaim +apiVersion: v1 +metadata: + name: {{ printf "rustus-data-%s" (include "rustus.fullname" .) }} + labels: + {{- include "rustus.selectorLabels" . | nindent 4 }} + {{- if .Values.persistence.annotations }} + annotations: {{- toYaml .Values.persistence.annotations | nindent 4 }} + {{- end }} +spec: + storageClassName: {{ .Values.persistence.storageClass }} + accessModes: + {{- range .Values.persistence.accessModes }} + - {{ . | quote }} + {{- end }} + {{- with .Values.persistence.dataSource }} + dataSource: + {{ . | toYaml | nindent 4 }} + {{- end }} + {{- with .Values.persistence.selector }} + selector: + {{- . | toYaml | nindent 4 }} + {{- end }} + mountOptions: + {{- .Values.persistence.mountOptions | toYaml | nindent 4 }} + resources: + requests: + storage: {{ .Values.persistence.size | quote }} +{{- end }} \ No newline at end of file diff --git a/deploy/helm/templates/service.yaml b/deploy/helm/templates/service.yaml new file mode 100644 index 0000000..3143da2 --- /dev/null +++ b/deploy/helm/templates/service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "rustus.fullname" . }} + labels: + {{- include "rustus.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + name: http + selector: + {{- include "rustus.selectorLabels" . | nindent 4 }} diff --git a/deploy/helm/templates/serviceaccount.yaml b/deploy/helm/templates/serviceaccount.yaml new file mode 100644 index 0000000..9118fa4 --- /dev/null +++ b/deploy/helm/templates/serviceaccount.yaml @@ -0,0 +1,12 @@ +{{- if .Values.serviceAccount.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "rustus.serviceAccountName" . }} + labels: + {{- include "rustus.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/deploy/helm/values.yaml b/deploy/helm/values.yaml new file mode 100644 index 0000000..a062c48 --- /dev/null +++ b/deploy/helm/values.yaml @@ -0,0 +1,180 @@ +# Default values for rustus. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +replicaCount: 1 + +image: + repository: s3rius/rustus + pullPolicy: IfNotPresent + # Overrides the image tag whose default is the chart appVersion. + tag: "" + command: [] + # command: + # - rustus + +env: + RUSTUS_PORT: 1081 + RUSTUS_DATA_DIR: /data + RUSTUS_INFO_DIR: /data + RUSTUS_DIR_STRUCTURE: "{year}/{month}/{day}" + +# For redis info storage +# RUSTUS_INFO_STORAGE: redis-info-storage +# RUSTUS_INFO_DB_DSN: redis://:pass@rustus-redis-master/0 + +# For postgresql info storage +# RUSTUS_INFO_STORAGE: db-info-storage +# RUSTUS_INFO_DB_DSN: postgresql://rustus:rustus@rustus-postgresql/rustus + +# For MySQL info storage +# RUSTUS_INFO_STORAGE: db-info-storage +# RUSTUS_INFO_DB_DSN: mysql://rustus:rustus@rustus-mysql/rustus + +persistence: + enabled: false + + # Existing pvc to use + existingClaim: "" + + # Options for creating pvc + accessModes: + - ReadWriteOnce + size: 1Gi + storageClass: local-path + mountOptions: {} + selector: {} + annotations: {} + dataSource: {} + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +serviceAccount: + # Specifies whether a service account should be created + create: true + # Annotations to add to the service account + annotations: {} + # The name of the service account to use. + # If not set and create is true, a name is generated using the fullname template + name: "" + +podAnnotations: {} + +podSecurityContext: {} +# fsGroup: 2000 + +securityContext: + {} + # capabilities: + # drop: + # - ALL + # readOnlyRootFilesystem: true +# runAsNonRoot: true +# runAsUser: 1000 + +service: + type: ClusterIP + port: 80 + +ingress: + enabled: false + className: "" + annotations: {} + # kubernetes.io/ingress.class: nginx + # kubernetes.io/tls-acme: "true" + hosts: + - host: rustus.localhost + paths: + - path: / + pathType: Prefix + tls: [] + # - secretName: chart-example-tls + # hosts: + # - chart-example.local + +resources: + {} + # We usually recommend not to specify default resources and to leave this as a conscious + # choice for the user. This also increases chances charts run on environments with little + # resources, such as Minikube. If you do want to specify resources, uncomment the following + # lines, adjust them as necessary, and remove the curly braces after 'resources:'. + # limits: + # cpu: 100m + # memory: 128Mi + # requests: +# cpu: 100m +# memory: 128Mi + +autoscaling: + enabled: false + minReplicas: 1 + maxReplicas: 100 + targetCPUUtilizationPercentage: 80 + # targetMemoryUtilizationPercentage: 80 + +nodeSelector: {} + +tolerations: [] + +affinity: {} + +# Configuration for redis sub-chart +redis: + # After enabling this parameter + # you should set info-storage to redis-info-storage + # and provide valid connection string. + # You can do it using following env variables: + # RUSTUS_INFO_STORAGE: redis-info-storage + # RUSTUS_INFO_DB_DSN: redis://:pass@rustus-redis-master/0 + + enabled: false + + global: + redis: + # ! Override values for production use + password: "pass" + + master: + persistence: + # ! Override values for production use + enabled: false + + service: + type: ClusterIP + +# Configuration for postgresql sub-chart +postgresql: + # After enabling this parameter + # you should set info-storage to db-info-storage + # and provide valid connection string. + # You can do it using following env variables: + # RUSTUS_INFO_STORAGE: db-info-storage + # RUSTUS_INFO_DB_DSN: postgresql://rustus:rustus@rustus-postgresql/rustus + + enabled: false + + global: + postgresql: + auth: + # ! Override values for production use + username: rustus + password: rustus + database: rustus + +mysql: + # After enabling this parameter + # you should set info-storage to db-info-storage + # and provide valid connection string. + # You can do it using following env variables: + # RUSTUS_INFO_STORAGE: db-info-storage + # RUSTUS_INFO_DB_DSN: mysql://rustus:rustus@rustus-mysql/rustus + + enabled: false + + auth: + # ! Override values for production use + database: rustus + username: rustus + password: rustus diff --git a/src/config.rs b/src/config.rs index 50b8b79..ae38eaa 100644 --- a/src/config.rs +++ b/src/config.rs @@ -189,7 +189,7 @@ pub struct RustusConf { /// Enabled extensions for TUS protocol. #[structopt( long, - default_value = "getting,creation,termination,creation-with-upload,creation-defer-length,concatenation", + default_value = "getting,creation,termination,creation-with-upload,creation-defer-length,concatenation,checksum", env = "RUSTUS_TUS_EXTENSIONS", use_delimiter = true )] diff --git a/src/errors.rs b/src/errors.rs index c2a4f49..13ad2ae 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -59,6 +59,12 @@ pub enum RustusError { StdError(#[from] std::io::Error), #[error("Can't spawn task: {0}")] TokioSpawnError(#[from] tokio::task::JoinError), + #[error("Unknown hashsum algorithm")] + UnknownHashAlgorithm, + #[error("Wrong checksum")] + WrongChecksum, + #[error("The header value is incorrect")] + WrongHeaderValue, } /// This conversion allows us to use `RustusError` in the `main` function. @@ -83,9 +89,12 @@ impl ResponseError for RustusError { match self { RustusError::FileNotFound => StatusCode::NOT_FOUND, RustusError::WrongOffset => StatusCode::CONFLICT, - RustusError::FrozenFile | RustusError::SizeAlreadyKnown | RustusError::HookError(_) => { - StatusCode::BAD_REQUEST - } + RustusError::FrozenFile + | RustusError::SizeAlreadyKnown + | RustusError::HookError(_) + | RustusError::UnknownHashAlgorithm + | RustusError::WrongHeaderValue => StatusCode::BAD_REQUEST, + RustusError::WrongChecksum => StatusCode::EXPECTATION_FAILED, _ => StatusCode::INTERNAL_SERVER_ERROR, } } diff --git a/src/main.rs b/src/main.rs index 16713c6..6fc08e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -93,6 +93,7 @@ pub fn create_server(state: State) -> Result { } srv.call(req) }) + .route("/health", web::get().to(routes::health_check)) // Default response for unknown requests. // It returns 404 status_code. .default_service(web::route().to(routes::not_found)) diff --git a/src/protocol/core/server_info.rs b/src/protocol/core/server_info.rs index 3648e84..41d1e2f 100644 --- a/src/protocol/core/server_info.rs +++ b/src/protocol/core/server_info.rs @@ -1,4 +1,6 @@ -use actix_web::{web, HttpResponse}; +#[cfg(feature = "hashers")] +use crate::protocol::extensions::Extensions; +use actix_web::{http::StatusCode, web, HttpResponse, HttpResponseBuilder}; use crate::State; @@ -12,9 +14,13 @@ pub async fn server_info(state: web::Data) -> HttpResponse { .map(|x| x.to_string()) .collect::>() .join(","); - HttpResponse::Ok() - .insert_header(("Tus-Extension", ext_str.as_str())) - .finish() + let mut response_builder = HttpResponseBuilder::new(StatusCode::OK); + response_builder.insert_header(("Tus-Extension", ext_str.as_str())); + #[cfg(feature = "hashers")] + if state.config.tus_extensions.contains(&Extensions::Checksum) { + response_builder.insert_header(("Tus-Checksum-Algorithm", "md5,sha1,sha256,sha512")); + } + response_builder.finish() } #[cfg(test)] diff --git a/src/protocol/core/write_bytes.rs b/src/protocol/core/write_bytes.rs index 49418ab..fafc64e 100644 --- a/src/protocol/core/write_bytes.rs +++ b/src/protocol/core/write_bytes.rs @@ -1,5 +1,7 @@ use actix_web::{web, web::Bytes, HttpRequest, HttpResponse}; +#[cfg(feature = "hashers")] +use crate::utils::hashes::verify_chunk_checksum; use crate::{ errors::RustusError, notifiers::Hook, @@ -29,6 +31,20 @@ pub async fn write_bytes( return Err(RustusError::FileNotFound); } + #[cfg(feature = "hashers")] + if state.config.tus_extensions.contains(&Extensions::Checksum) { + if let Some(header) = request.headers().get("Upload-Checksum").cloned() { + let cloned_bytes = bytes.clone(); + if !tokio::task::spawn_blocking(move || { + verify_chunk_checksum(&header, cloned_bytes.as_ref()) + }) + .await?? + { + return Err(RustusError::WrongChecksum); + } + } + } + // New upload length. // Parses header `Upload-Length` only if the creation-defer-length extension is enabled. let updated_len = if state @@ -151,6 +167,7 @@ mod tests { let request = TestRequest::patch() .uri(state.config.file_url(file.id.as_str()).as_str()) .insert_header(("Content-Type", "application/offset+octet-stream")) + .insert_header(("Upload-Checksum", "md5 xIwpFX4rNYzBRAJ/Pi2MtA==")) .insert_header(("Upload-Offset", file.offset)) .set_payload(test_data) .to_request(); @@ -418,4 +435,27 @@ mod tests { let resp = call_service(&mut rustus, request).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); } + + #[actix_rt::test] + /// Tests checksum validation. + async fn wrong_checksum() { + let state = State::test_new().await; + let mut rustus = init_service( + App::new().configure(rustus_service(web::Data::new(state.test_clone().await))), + ) + .await; + let mut file = state.create_test_file().await; + file.offset = 0; + file.length = Some(10); + state.info_storage.set_info(&file, false).await.unwrap(); + let request = TestRequest::patch() + .uri(state.config.file_url(file.id.as_str()).as_str()) + .insert_header(("Upload-Offset", "0")) + .insert_header(("Upload-Checksum", "md5 K9opmNmw7hl9oUKgRH9nJQ==")) + .insert_header(("Content-Type", "application/offset+octet-stream")) + .set_payload("memes") + .to_request(); + let resp = call_service(&mut rustus, request).await; + assert_eq!(resp.status(), StatusCode::EXPECTATION_FAILED); + } } diff --git a/src/protocol/extensions.rs b/src/protocol/extensions.rs index 4eba162..9847523 100644 --- a/src/protocol/extensions.rs +++ b/src/protocol/extensions.rs @@ -18,6 +18,8 @@ pub enum Extensions { Concatenation, #[display(fmt = "getting")] Getting, + #[display(fmt = "checksum")] + Checksum, } from_str!(Extensions, "extension"); diff --git a/src/routes.rs b/src/routes.rs index 9dca6f6..6a07692 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -10,3 +10,10 @@ use crate::errors::{RustusError, RustusResult}; pub async fn not_found() -> RustusResult { Err(RustusError::FileNotFound) } + +/// Checks that application is accepting connections correctly. +#[allow(clippy::unused_async)] +#[cfg_attr(coverage, no_coverage)] +pub async fn health_check() -> HttpResponse { + HttpResponse::Ok().finish() +} diff --git a/src/storages/file_storage.rs b/src/storages/file_storage.rs index 86bf09d..29c431b 100644 --- a/src/storages/file_storage.rs +++ b/src/storages/file_storage.rs @@ -144,8 +144,9 @@ impl Storage for FileStorage { parts_info: Vec, ) -> RustusResult<()> { let info = file_info.clone(); + let force_fsync = self.force_fsync; tokio::task::spawn_blocking(move || { - let mut file = OpenOptions::new() + let file = OpenOptions::new() .write(true) .append(true) .create(true) @@ -154,6 +155,7 @@ impl Storage for FileStorage { error!("{:?}", err); RustusError::UnableToWrite(err.to_string()) })?; + let mut writer = BufWriter::new(file); for part in parts_info { if part.path.is_none() { return Err(RustusError::FileNotFound); @@ -162,9 +164,12 @@ impl Storage for FileStorage { .read(true) .open(part.path.as_ref().unwrap())?; let mut reader = BufReader::new(part_file); - copy(&mut reader, &mut file)?; + copy(&mut reader, &mut writer)?; + } + writer.flush()?; + if force_fsync { + writer.get_ref().sync_data()?; } - file.sync_data()?; Ok(()) }) .await? diff --git a/src/utils/hashes.rs b/src/utils/hashes.rs new file mode 100644 index 0000000..28536ee --- /dev/null +++ b/src/utils/hashes.rs @@ -0,0 +1,128 @@ +use crate::{errors::RustusError, RustusResult}; +use actix_web::http::header::HeaderValue; +use digest::Digest; + +/// Checks if hash-sum of a slice matches the given checksum. +fn checksum_verify(algo: &str, bytes: &[u8], checksum: &[u8]) -> RustusResult { + match algo { + "sha1" => { + let sum = sha1::Sha1::digest(bytes); + Ok(sum.as_slice() == checksum) + } + "sha256" => { + let sum = sha2::Sha256::digest(bytes); + Ok(sum.as_slice() == checksum) + } + "sha512" => { + let sum = sha2::Sha512::digest(bytes); + Ok(sum.as_slice() == checksum) + } + "md5" => { + let sum = md5::Md5::digest(bytes); + Ok(sum.as_slice() == checksum) + } + _ => Err(RustusError::UnknownHashAlgorithm), + } +} + +/// Verify checksum of a given chunk based on header's value. +/// +/// This function decodes given header value. +/// Format of the header is: +/// +/// +/// It tries decode header value to string, +/// splits it in two parts and after decoding base64 checksum +/// verifies it. +/// +/// # Errors +/// +/// It may return error if header value can't be represented as string, +/// if checksum can't be decoded with base64 or if unknown algorithm is used. +pub fn verify_chunk_checksum(header: &HeaderValue, data: &[u8]) -> RustusResult { + if let Ok(val) = header.to_str() { + let mut split = val.split(' '); + if let Some(algo) = split.next() { + if let Some(checksum_base) = split.next() { + let checksum = base64::decode(checksum_base).map_err(|_| { + log::error!("Can't decode checksum value"); + RustusError::WrongHeaderValue + })?; + return checksum_verify(algo, data, checksum.as_slice()); + } + } + Err(RustusError::WrongHeaderValue) + } else { + log::error!("Can't decode checksum header."); + Err(RustusError::WrongHeaderValue) + } +} + +#[cfg(test)] +mod tests { + use super::{checksum_verify, verify_chunk_checksum}; + use actix_web::http::header::HeaderValue; + + #[test] + fn test_success_checksum_verify() { + let res = checksum_verify( + "sha1", + b"hello", + b"\xaa\xf4\xc6\x1d\xdc\xc5\xe8\xa2\xda\xbe\xde\x0f;H,\xd9\xae\xa9CM", + ) + .unwrap(); + assert!(res); + let res = checksum_verify( + "sha256", + b"hello", + b",\xf2M\xba_\xb0\xa3\x0e&\xe8;*\xc5\xb9\xe2\x9e\x1b\x16\x1e\\\x1f\xa7B^s\x043b\x93\x8b\x98$", + ).unwrap(); + assert!(res); + let res = checksum_verify( + "sha512", + b"hello", + b"\x9bq\xd2$\xbdb\xf3x]\x96\xd4j\xd3\xea=s1\x9b\xfb\xc2\x89\x0c\xaa\xda\xe2\xdf\xf7%\x19g<\xa7##\xc3\xd9\x9b\xa5\xc1\x1d|z\xccn\x14\xb8\xc5\xda\x0cFcG\\.\\:\xde\xf4os\xbc\xde\xc0C", + ).unwrap(); + assert!(res); + let res = + checksum_verify("md5", b"hello", b"]A@*\xbcK*v\xb9q\x9d\x91\x10\x17\xc5\x92").unwrap(); + assert!(res); + } + + #[test] + fn test_sum_unknown_algo_checksum_verify() { + let res = checksum_verify("base64", "test".as_bytes(), b"dGVzdAo="); + assert!(res.is_err()); + } + + #[test] + fn test_success_verify_chunk_checksum() { + let res = verify_chunk_checksum( + &HeaderValue::from_str("md5 XUFAKrxLKna5cZ2REBfFkg==").unwrap(), + b"hello", + ) + .unwrap(); + assert!(res); + } + + #[test] + fn test_wrong_checksum() { + let res = verify_chunk_checksum(&HeaderValue::from_str("md5 memes==").unwrap(), b"hello"); + assert!(res.is_err()); + } + + #[test] + fn test_bytes_header() { + let res = verify_chunk_checksum( + &HeaderValue::from_bytes(b"ewq ]A@*\xbcK*v").unwrap(), + b"hello", + ); + assert!(res.is_err()); + } + + #[test] + fn test_badly_formatted_header() { + let res = verify_chunk_checksum(&HeaderValue::from_str("md5").unwrap(), b"hello"); + assert!(res.is_err()); + } +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 0bef5e2..458aa2c 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,3 +1,5 @@ pub mod dir_struct; pub mod enums; +#[cfg(feature = "hashers")] +pub mod hashes; pub mod headers;