1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use super::{with_state, AppState};
use crate::{certs::Cert, server::rpc::certs::*};
use hyper::Response;
use std::{io::Read, ops::Deref, sync::Arc};
use taxy_api::{
    cert::{SelfSignedCertRequest, UploadQuery},
    error::Error,
    id::ShortId,
};
use tokio_stream::StreamExt;
use warp::{filters::BoxedFilter, multipart::FormData, Buf, Filter, Rejection, Reply};

pub fn api(app_state: AppState) -> BoxedFilter<(impl Reply,)> {
    let api_list = warp::get()
        .and(warp::path::end())
        .and(with_state(app_state.clone()).and_then(list));

    let api_get = warp::get().and(
        with_state(app_state.clone())
            .and(warp::path::param())
            .and(warp::path::end())
            .and_then(get),
    );

    let api_self_sign = warp::post().and(warp::path("self_sign")).and(
        with_state(app_state.clone())
            .and(warp::body::json())
            .and(warp::path::end())
            .and_then(self_sign),
    );

    let api_upload = warp::post().and(warp::path("upload")).and(
        with_state(app_state.clone())
            .and(warp::multipart::form())
            .and(warp::query())
            .and(warp::path::end())
            .and_then(upload),
    );

    let api_delete = warp::delete().and(
        with_state(app_state.clone())
            .and(warp::path::param())
            .and(warp::path::end())
            .and_then(delete),
    );

    let api_download = warp::get().and(
        with_state(app_state)
            .and(warp::path::param())
            .and(warp::path("download"))
            .and(warp::path::end())
            .and_then(download),
    );

    warp::path("certs")
        .and(
            api_delete
                .or(api_get)
                .or(api_download)
                .or(api_self_sign)
                .or(api_upload)
                .or(api_list),
        )
        .boxed()
}

/// List server certificates.
#[utoipa::path(
    get,
    path = "/api/certs",
    responses(
        (status = 200, body = [CertInfo]),
        (status = 401),
    ),
    security(
        ("cookie"=[])
    )
)]
pub async fn list(state: AppState) -> Result<impl Reply, Rejection> {
    Ok(warp::reply::json(&state.call(GetCertList).await?))
}

/// Delete a certificate.
#[utoipa::path(
    get,
    path = "/api/certs/{id}",
    params(
        ("id" = String, Path, description = "Certification ID")
    ),
    responses(
        (status = 200, body = [CertInfo]),
        (status = 404),
        (status = 401),
    ),
    security(
        ("cookie"=[])
    )
)]
pub async fn get(state: AppState, id: ShortId) -> Result<impl Reply, Rejection> {
    Ok(warp::reply::json(&state.call(GetCert { id }).await?.info()))
}

/// Generate a self-signed certificate.
#[utoipa::path(
    post,
    path = "/api/certs/self_sign",
    request_body = SelfSignedCertRequest,
    responses(
        (status = 200),
        (status = 400, body = Error),
        (status = 401),
    ),
    security(
        ("cookie"=[])
    )
)]
pub async fn self_sign(
    state: AppState,
    request: SelfSignedCertRequest,
) -> Result<impl Reply, Rejection> {
    let cert = if let Some(ca_cert) = request.ca_cert {
        let ca = state.call(GetCert { id: ca_cert }).await?;
        Cert::new_self_signed(&request.san, &ca)?
    } else {
        let ca = Arc::new(Cert::new_ca()?);
        state.call(AddCert { cert: ca.clone() }).await?;
        Cert::new_self_signed(&request.san, &ca)?
    };
    let cert = Arc::new(cert);
    Ok(warp::reply::json(&state.call(AddCert { cert }).await?))
}

/// Upload a certificate and key pair.
#[utoipa::path(
    post,
    path = "/api/certs/upload",
    request_body(content = CertPostBody, content_type = "multipart/form-data"),
    params(UploadQuery),
    responses(
        (status = 200),
        (status = 400, body = Error),
        (status = 401),
    ),
    security(
        ("cookie"=[])
    )
)]
pub async fn upload(
    state: AppState,
    mut form: FormData,
    query: UploadQuery,
) -> Result<impl Reply, Rejection> {
    let mut chain = Vec::new();
    let mut key = Vec::new();
    while let Some(part) = form.next().await {
        if let Ok(mut part) = part {
            if part.name() == "chain" {
                if let Some(Ok(buf)) = part.data().await {
                    buf.reader()
                        .read_to_end(&mut chain)
                        .map_err(|_| Error::FailedToReadCertificate)?;
                }
            } else if part.name() == "key" {
                if let Some(Ok(buf)) = part.data().await {
                    buf.reader()
                        .read_to_end(&mut key)
                        .map_err(|_| Error::FailedToReadPrivateKey)?;
                }
            }
        }
    }

    let key = if key.is_empty() { None } else { Some(key) };
    let cert = Arc::new(Cert::new(query.kind, chain, key)?);
    Ok(warp::reply::json(&state.call(AddCert { cert }).await?))
}

/// Delete a certificate.
#[utoipa::path(
    delete,
    path = "/api/certs/{id}",
    params(
        ("id" = String, Path, description = "Certification ID")
    ),
    responses(
        (status = 200),
        (status = 404),
        (status = 401),
    ),
    security(
        ("cookie"=[])
    )
)]
pub async fn delete(state: AppState, id: ShortId) -> Result<impl Reply, Rejection> {
    Ok(warp::reply::json(&state.call(DeleteCert { id }).await?))
}

/// Download a certificate.
#[utoipa::path(
    get,
    path = "/api/certs/{id}/download",
    params(
        ("id" = String, Path, description = "Certification ID")
    ),
    responses(
        (status = 200, body = Vec<u8>),
        (status = 404),
        (status = 401),
    ),
    security(
        ("cookie"=[])
    )
)]
pub async fn download(state: AppState, id: ShortId) -> Result<impl Reply, Rejection> {
    let file = state.call(DownloadCert { id }).await?;
    Ok(Response::builder()
        .header("Content-Type", "application/gzip")
        .header(
            "Content-Disposition",
            &format!("attachment; filename=\"{}.tar.gz\"", id),
        )
        .body(file.deref().clone())
        .unwrap())
}