forked from mtusi2026/mtusi2026lab7
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
883b3e0305 |
@@ -0,0 +1 @@
|
||||
{"DB_USERNAME": "api", "DB_PASSWORD": "cf0cf210a4d48d3ec335fbaa9d43a25731f58f32cead642d", "RABBITMQ_USER": "api", "RABBITMQ_PASSWORD": "4f15f189a145c0de501b440f6588b098d76eff804bbb6040", "S3_ACCESS_KEY": "messenger_api", "S3_SECRET_KEY": "8209f770e1a62dbadca5812001b1022e6067067dac9774d6", "REDIS_PASSWORD": "df82514253c692abd7ad171bc3ba7c75610cd6784c9b5c8b", "SPRING_DATA_REDIS_USERNAME": "api"}
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBnTCCAUOgAwIBAgIUd5psHnGr5P+DqwS9ROeQe+BSbIEwCgYIKoZIzj0EAwIw
|
||||
HDEaMBgGA1UEAwwRTWVzc2VuZ2VyIExhYjcgQ0EwHhcNMjYxMTIyMTY0NzA1WhcN
|
||||
MjcxMTIyMTY0NzA1WjAcMRowGAYDVQQDDBFNZXNzZW5nZXIgTGFiNyBDQTBZMBMG
|
||||
ByqGSM49AgEGCCqGSM49AwEHA0IABLcIZQ4vpjOPRFMl2fQMb/Xhdyw8B2XaYCUD
|
||||
IbZjXWwq/yhxdYmLSFuJqb30AQpIc46r/+KZx7EceS9l/Y+lESujYzBhMB0GA1Ud
|
||||
DgQWBBTjaSuY/j54Tx9Q/5JuGNu8hwwD7DAfBgNVHSMEGDAWgBTjaSuY/j54Tx9Q
|
||||
/5JuGNu8hwwD7DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggq
|
||||
hkjOPQQDAgNIADBFAiEAlCfOK/vw7ud3a5O9hR/FOC96u7SrDjXhl0pRvzy4HeIC
|
||||
IBNWCX1q3LrMRH7R3oGW4ey8FIm2mlVy+BPIRxqc1kp1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1 @@
|
||||
{"vhosts": [{"name": "/"}], "users": [{"name": "api", "tags": [], "hashing_algorithm": "rabbit_password_hashing_sha256", "password_hash": "6/OWXQIhdHAb5Y+HNRbAKmgsE/Pbyb6/6kPBwdsK8peERtQu"}, {"name": "worker", "tags": [], "hashing_algorithm": "rabbit_password_hashing_sha256", "password_hash": "Gudvczf7zSnGMDLzMAFAmZDkeKC5uczr6Arl6rVJYmmVkMOE"}], "permissions": [{"user": "api", "vhost": "/", "configure": "^$", "write": "^amq[.]default$", "read": "^$"}, {"user": "worker", "vhost": "/", "configure": "^$", "write": "^$", "read": "^attachments[.]v1$"}], "queues": [{"name": "attachments.v1", "vhost": "/", "durable": true, "auto_delete": false, "arguments": {"x-dead-letter-exchange": "", "x-dead-letter-routing-key": "attachments.v1.dlq"}}, {"name": "attachments.v1.dlq", "vhost": "/", "durable": true, "auto_delete": false, "arguments": {}}]}
|
||||
@@ -0,0 +1,2 @@
|
||||
user default off
|
||||
user api on #08de8e1c2367f34ebf71f20bfbd41412bf51b8839934df2c84766f04984cff34 ~session:* +get +set +psetex +setex +del +ping +hello +client|setname +client|setinfo +select
|
||||
@@ -0,0 +1,2 @@
|
||||
CREATE ROLE api LOGIN PASSWORD 'cf0cf210a4d48d3ec335fbaa9d43a25731f58f32cead642d';
|
||||
CREATE ROLE worker LOGIN PASSWORD 'e0cef7df6fea57e01f5222e5d578e606ff189544d80be654';
|
||||
@@ -0,0 +1 @@
|
||||
{"DB_USERNAME": "worker", "DB_PASSWORD": "e0cef7df6fea57e01f5222e5d578e606ff189544d80be654", "RABBITMQ_USER": "worker", "RABBITMQ_PASSWORD": "295e3597233d4d8f64bd693b94d80ba8bf2e25fb00889089", "S3_ACCESS_KEY": "messenger_worker", "S3_SECRET_KEY": "2ca4df7e3adb88d4da3d9e3cce49670d6162fadc4b21f758"}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
|
||||
|
||||
|
||||
FROM maven:3.9.9-eclipse-temurin-21 AS build
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
COPY java/pom.xml ./pom.xml
|
||||
|
||||
RUN mvn -B dependency:go-offline
|
||||
|
||||
COPY java/src ./src
|
||||
|
||||
RUN mvn -B package -DskipTests
|
||||
|
||||
|
||||
FROM eclipse-temurin:21.0.9_10-jre-jammy
|
||||
|
||||
RUN sed -i 's|http://archive.ubuntu.com|https://archive.ubuntu.com|g; s|http://security.ubuntu.com|https://security.ubuntu.com|g' /etc/apt/sources.list \
|
||||
&& apt-get -o Acquire::Retries=3 update \
|
||||
&& apt-get -o Acquire::Retries=3 install -y --no-install-recommends \
|
||||
python3 \
|
||||
python3-venv \
|
||||
haproxy wget \
|
||||
&& python3 -m venv /opt/images \
|
||||
&& /opt/images/bin/pip install --no-cache-dir Pillow==12.0.0 \
|
||||
&& /opt/images/bin/python -c \
|
||||
"from PIL import features; assert features.check('webp')" \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --system --uid 1001 --create-home app
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=build /build/target/*.jar /app/app.jar
|
||||
|
||||
COPY infra/images/process_image.py /app/process_image.py
|
||||
COPY infra/images/selftest.py /app/selftest.py
|
||||
|
||||
COPY infra/app-start.py /app/start.py
|
||||
|
||||
USER 1001
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["python3", "/app/start.py"]
|
||||
@@ -1,6 +1,6 @@
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= https://localhost:8443
|
||||
CA_FILE ?=
|
||||
CA_FILE ?= .local/ca.crt
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
@@ -31,3 +31,17 @@ test-failover:
|
||||
|
||||
test-security:
|
||||
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
.PHONY: benchmark test-expiry security-extra
|
||||
|
||||
benchmark:
|
||||
docker compose exec -T api java -XX:MaxRAMPercentage=25 -Dloader.main=com.vnp.demo.config.PasswordBenchmark -cp /app/app.jar org.springframework.boot.loader.launch.PropertiesLauncher
|
||||
|
||||
test-expiry:
|
||||
@set -e; trap 'docker compose up -d --no-deps --wait api' EXIT; \
|
||||
SESSION_TTL_SECONDS=5 docker compose up -d --no-deps --wait api; \
|
||||
$(PYTHON) tests/negative_api.py --expiry --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
security-extra:
|
||||
$(PYTHON) tests/negative_api.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
docker compose run --rm --no-deps probe
|
||||
|
||||
@@ -1,37 +1,137 @@
|
||||
# Отчёт — лабораторная 7
|
||||
# Лабораторная работа 7.
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
**Автор:** Хуцаева, группа БПИ2302.
|
||||
**Целевая оценка:** 3.
|
||||
**Commit/PR:** solution/khutsaeva-bpi2302
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
## Запуск из чистого клона
|
||||
|
||||
Стенд запускался в Windows 11 с Docker Desktop и Ubuntu в WSL. Использовались Docker Compose 5.5.1, Python 3.14 и OpenSSL. Для сборки приложения Docker использует Maven 3.9.9 и Java 21, для запуска — Eclipse Temurin 21.0.9. Основные сервисы — nginx 1.28, HAProxy 3.0.5, OpenBao 2.4.4, PostgreSQL 16.6, Redis 7.4.1 и RabbitMQ 4.1.4. MinIO собирается из исходников релиза от 22.04.2025. Версии образов мониторинга закреплены в compose.yml.
|
||||
|
||||
### 1. Подготовка
|
||||
|
||||
Команды выполняются в Ubuntu из корня клона, где расположен compose.yml. Для первого запуска нужны доступ к реестрам образов и репозиториям зависимостей, свободные локальные порты 8443, 8200 и 3443. Рабочий каталог в файловой системе Linux позволяет использовать обычные права доступа к ключам.
|
||||
|
||||
~~~bash
|
||||
sudo apt install -y python3.14-venv make openssl
|
||||
python3 -m venv ~/.venvs/mtusi-lab7
|
||||
source ~/.venvs/mtusi-lab7/bin/activate
|
||||
python -m pip install -r requirements-dev.txt
|
||||
chmod +x scripts/*.sh
|
||||
export LAB7_OPERATOR_DIR="$HOME/.messenger7-operator"
|
||||
python3 scripts/bootstrap.py
|
||||
python3 scripts/check-layout.py
|
||||
docker compose config --quiet
|
||||
~~~
|
||||
|
||||
Для нового стенда bootstrap создаёт локальный .env, сертификаты, ключи сервисов и данные для первичной настройки зависимостей. Закрытый ключ CA хранится в каталоге оператора вне проекта. Файлы .env, .local/ и операторские ключи исключаются из публикации.
|
||||
|
||||
### 2. Инициализация OpenBao
|
||||
|
||||
~~~bash
|
||||
docker compose up -d openbao
|
||||
docker compose exec openbao bao status
|
||||
~~~
|
||||
|
||||
При первом запуске статус показывает Initialized false и Sealed true. Только в этом состоянии оператор инициализирует новый том. Результат содержит секреты и сохраняется в закрытом файле вне репозитория.
|
||||
|
||||
~~~bash
|
||||
(umask 077; set -C; docker compose exec -T openbao bao operator init \
|
||||
-key-shares=1 -key-threshold=1 -format=json > "$LAB7_OPERATOR_DIR/init.json")
|
||||
docker compose exec openbao bao operator unseal
|
||||
python3 scripts/configure-bao.py
|
||||
~~~
|
||||
|
||||
В приглашение unseal оператор вводит первый элемент unseal_keys_b64 из init.json. В приглашение configure-bao.py вводится root_token из того же файла. Скрипт настраивает cert auth, две политики и две записи KV. После перезапуска существующего OpenBao при Sealed true достаточно повторить unseal сохранённым ключом.
|
||||
|
||||
### 3. Сборка, миграции и проверки
|
||||
|
||||
~~~bash
|
||||
docker compose build minio api
|
||||
docker compose up -d --wait --wait-timeout 300
|
||||
curl --fail --cacert .local/ca.crt https://localhost:8443/health/ready
|
||||
bash scripts/verify.sh
|
||||
~~~
|
||||
|
||||
Flyway выполняет миграции, включая V7 с правами ролей api и worker. Сервис minio-init создаёт приватный бакет и политики доступа. Оба контейнера завершают работу после настройки. В проверенном запуске запрос готовности вернул {"status":"ok"}. Полный журнал сценария сохраняется в evidence/stand.txt.
|
||||
|
||||
### 4. Остановка
|
||||
|
||||
Обычная остановка с сохранением данных и состояния OpenBao:
|
||||
|
||||
~~~bash
|
||||
docker compose down
|
||||
~~~
|
||||
|
||||
Отдельная команда для **намеренного удаления учебных данных**, включая том OpenBao:
|
||||
|
||||
~~~bash
|
||||
docker compose down -v
|
||||
~~~
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
~~~mermaid
|
||||
flowchart TD
|
||||
C["Клиент"] -->|HTTPS| LB["nginx"]
|
||||
LB -->|mTLS| A["Две реплики API"]
|
||||
A --> PG["PostgreSQL"]
|
||||
A --> R["Redis"]
|
||||
A --> S["MinIO"]
|
||||
A --> Q["RabbitMQ"]
|
||||
Q --> W["Worker"]
|
||||
W --> PG
|
||||
W --> S
|
||||
~~~
|
||||
|
||||
Из lab6 перенесены бизнес-API, две реплики, хранение сообщений и вложений, обработка изображений и мониторинг. В lab7 добавлены проверяемый HTTPS, обязательный mTLS от nginx до каждой реплики, ограничения входа, отдельные права сервисов и получение секретов через OpenBao.
|
||||
|
||||
**Хранение и транзакции.** PostgreSQL хранит пользователей, сообщения, метаданные вложений, состояние заданий и записи о сессиях. Redis хранит активные сессии с TTL. MinIO хранит исходные файлы и варианты изображений. API загружает файл во временный префикс staging, затем фиксирует метаданные, задание и запись outbox в одной транзакции PostgreSQL. Фоновый обработчик получает задание через RabbitMQ, сохраняет результат в MinIO и подтверждает доставку после фиксации состояния в БД. Записи в S3 и PostgreSQL имеют разные границы фиксации.
|
||||
|
||||
**Транспорт и идентификация.** Клиент проверяет CA и имя localhost. nginx проверяет сертификат API и предъявляет свой сертификат. HAProxy внутри каждой реплики проверяет цепочку и разрешённую роль lb, затем передаёт запрос Java по loopback. Порт Java на хост не опубликован. Соединения между сервисами и хранилищами защищены TLS. Сервисы мониторинга используют ролевые TLS-шлюзы и выделенные локальные сети. Полная схема с портами, идентификаторами и локальными переходами приведена в [матрице доверия](contracts/trust-matrix.md), угрозы и ограничения — в [модели угроз](security/THREAT_MODEL.md).
|
||||
|
||||
**Секреты и права.** OpenBao работает с постоянным одноузловым Raft-хранилищем. При старте API и worker проходят аутентификацию своим сертификатом и получают токен на 2 минуты с максимальным TTL 5 минут. Политика допускает чтение своей записи KV. Приложения работают под UID 1001 со снятыми Linux capabilities, запретом повышения привилегий и лимитами ресурсов. На хост опубликованы только локальные порты nginx, OpenBao и Grafana.
|
||||
|
||||
| Параметры шаблона | Фактическая настройка |
|
||||
|---|---|
|
||||
| PUBLIC_BASE_URL, TLS_CA_FILE | Публичный адрес https://localhost:8443, для тестов CA_FILE=.local/ca.crt |
|
||||
| API_REPLICAS, SESSION_TTL_SECONDS | Две реплики, обычный TTL сессии 3600 с. В проверке истечения временно задаётся 5 с |
|
||||
| DATABASE_URL_FILE, CACHE_URL_FILE, BROKER_URL_FILE, S3_ACCESS_KEY_ID_FILE, S3_SECRET_ACCESS_KEY_FILE | Адреса задаёт Compose. infra/app-start.py читает из KV учётные данные своей роли. JDBC проверяет сервер в режиме verify-full. Ключи Redis ограничены префиксом session:* |
|
||||
| TLS_CERT_FILE, TLS_KEY_FILE, BAO_ADDR | Сертификат и ключ роли монтируются в /identity. Приложения обращаются к https://openbao:8200 |
|
||||
| S3_BUCKET, MAX_UPLOAD_BYTES | Приватный бакет messenger-attachments. Предел тела запроса на ingress — 10 MiB |
|
||||
| OTEL_SERVICE_NAME, OTEL_EXPORTER_OTLP_ENDPOINT | API и worker имеют разные service.name. Локальный адаптер направляет OTLP-трафик к Collector по защищённому соединению |
|
||||
| ARGON2_MEMORY_KIB, ARGON2_ITERATIONS, ARGON2_PARALLELISM | В PasswordConfig заданы 19456 KiB, 2 прохода и параллелизм 1. Соль 16 байт генерируется для каждого хеша |
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Команды ниже выполнялись в составе scripts/verify.sh. Для настроек, проверяемых чтением конфигурации, в последнем столбце указан соответствующий файл.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Критерий | Команда или сценарий | Результат | Доказательство |
|
||||
|---|---|---|---|
|
||||
| Контракт и бизнес-API по HTTPS | make check validate test | Структура, OpenAPI 3.1 и JSON Schema прошли проверку. Публичный сценарий прошёл от регистрации до получения оригинала и thumbnail | evidence/stand.txt |
|
||||
| Проверка CA и имени сервера | make test-security, make security-extra | С доверенным CA запрос успешен. Пустое хранилище доверия и неверное имя сервера вызвали ошибки проверки сертификата | evidence/stand.txt |
|
||||
| mTLS у каждой реплики | docker compose run --rm --no-deps probe | Обе реплики приняли сертификат LB и отклонили три случая: отсутствующий сертификат, чужой CA и запрещённая роль от доверенного CA | evidence/stand.txt, infra/tls/api.cfg |
|
||||
| Защита остальных связей | Проверка серверных и клиентских конфигураций, smoke с обработкой вложения | JDBC использует verify-full, соединения с Redis, MinIO, брокером и телеметрией проходят через настроенные TLS endpoints. Сквозной сценарий загрузки и обработки файла завершился успешно | contracts/trust-matrix.md, compose.yml, infra/tls/, evidence/stand.txt |
|
||||
| Хеширование пароля | make benchmark | Подтверждены Argon2id, заданные параметры и разные соли. Результаты замера приведены ниже | evidence/stand.txt |
|
||||
| Доступ к чатам и вложениям | make test, make security-extra | Посторонний пользователь получил 404 при чтении чужого вложения и попытке прикрепить его к сообщению в другом чате. Подмена X-User-Id не изменила Bearer-идентификацию | evidence/stand.txt |
|
||||
| Logout и истечение сессии | make test, make test-expiry | После выхода токен отклонён. При TTL 5 с токен сначала принят, спустя 6 с запрос получил 401. Обе реплики вернулись к обычной конфигурации | evidence/stand.txt |
|
||||
| Ограничения запросов | make security-extra, конфигурация nginx | Серия попыток входа привела к 429 с Retry-After. Предел тела 10 MiB задан директивой client_max_body_size; отдельный результат пробы на 413 в журнале отсутствует | evidence/stand.txt, infra/nginx.conf |
|
||||
| OpenBao и изоляция ролей | probe для api и worker | Обе роли прочитали свой KV. Чтение чужого пути и изменение policy отклонены. После отзыва токена повторное чтение получило 403 | evidence/stand.txt, infra/openbao/server.hcl |
|
||||
| Ограничение привилегий и портов | docker compose config --quiet, docker compose ps, просмотр Dockerfile | Для API и worker заданы UID, cap_drop, no-new-privileges, CPU и память. Порт 8080 у реплик без публикации на хост. У LB опубликован 127.0.0.1:8443 | Dockerfile, compose.yml, evidence/stand.txt |
|
||||
| Перезапуск и отказ реплики | make test-persistence, make test-failover с соответствующими ACTION_SCRIPT | Сессия и подтверждённые данные сохранились в обоих сценариях | evidence/stand.txt, scripts/restart.sh, scripts/stop-one.sh |
|
||||
|
||||
## Эксперименты и отказы
|
||||
## Измерения и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
**Argon2id.** Замер выполнен внутри работающего API с лимитами 1 CPU и 768 MiB. После пяти прогревочных вызовов выполнено 25 последовательных проверок пароля. При 19 MiB, t=2 и p=1 медиана составила **31 мс**, p95 — **138 мс**. Выбраны минимальные параметры задания: на этом стенде одна проверка укладывалась в указанные задержки, а память на вычисление одного хеша составляла 19 MiB плюс накладные расходы JVM. Замер характеризует вызов проверки пароля при последовательном выполнении.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Воздействие | Что делал сценарий | Наблюдение |
|
||||
|---|---|---|
|
||||
| Перезапуск процессов | restart.sh перезапустил PostgreSQL, Redis, MinIO, RabbitMQ, затем API, worker и nginx. Тома сохранены, OpenBao оставался запущенным | После восстановления клиент использовал прежнюю сессию и получил подтверждённые данные, включая содержимое вложения. Отдельное время восстановления не записано |
|
||||
| Остановка одной API-реплики | До остановки тест увидел два разных X-Instance-Id. stop-one.sh сопоставил выбранный идентификатор с контейнером и остановил его. Клиент продолжил обращения через HTTPS | За окно наблюдения выполнено **116 успешных записей, 0 неудачных попыток**. Первая успешная операция после начала остановки — через **0,66 с**. Подтверждённые данные и сессия доступны. После теста восстановлены две здоровые реплики |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Значение 0,66 с характеризует момент первого успешного обращения после начала воздействия. Длительность простоя по этому числу установить нельзя: в ходе прогона клиент не зарегистрировал ошибок.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
## Ограничения
|
||||
|
||||
Проверен отказ одной API-реплики на одном Docker-хосте. LB, OpenBao и хранилища развёрнуты в одном экземпляре. Оператор хранит одну долю unseal и вручную разблокирует OpenBao после его перезапуска. Отзыв токена OpenBao запрещает последующие чтения KV. Для отзыва уже выданного статического пароля требуется сменить его в соответствующем сервисе и обновить запись KV.
|
||||
|
||||
+608
@@ -0,0 +1,608 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.6-alpine
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:?}
|
||||
POSTGRES_USER: ${POSTGRES_USER:?}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?}
|
||||
command:
|
||||
- postgres
|
||||
- -c
|
||||
- max_connections=100
|
||||
- -c
|
||||
- shared_buffers=128MB
|
||||
- -c
|
||||
- ssl=on
|
||||
- -c
|
||||
- ssl_cert_file=/identity/cert.pem
|
||||
- -c
|
||||
- ssl_key_file=/tmp/server.key
|
||||
- -c
|
||||
- hba_file=/etc/postgres-hba.conf
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- .local/id/postgres:/identity:ro
|
||||
- ./infra/pg_hba.conf:/etc/postgres-hba.conf:ro
|
||||
- ./.local/roles.sql:/docker-entrypoint-initdb.d/010-roles.sql:ro
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"
|
||||
interval: 2s
|
||||
timeout: 1s
|
||||
retries: 30
|
||||
cpus: 1.0
|
||||
mem_limit: 512m
|
||||
networks:
|
||||
- mesh
|
||||
entrypoint:
|
||||
- /bin/sh
|
||||
- -ec
|
||||
- install -m 600 -o postgres /identity/key.pem /tmp/server.key; exec docker-entrypoint.sh
|
||||
"$@"
|
||||
- --
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
command:
|
||||
- redis-server
|
||||
- --aclfile
|
||||
- /etc/redis.acl
|
||||
- --appendonly
|
||||
- 'yes'
|
||||
- --maxmemory
|
||||
- 128mb
|
||||
- --maxmemory-policy
|
||||
- noeviction
|
||||
- --port
|
||||
- '0'
|
||||
- --tls-port
|
||||
- '6379'
|
||||
- --tls-cert-file
|
||||
- /identity/cert.pem
|
||||
- --tls-key-file
|
||||
- /identity/key.pem
|
||||
- --tls-ca-cert-file
|
||||
- /identity/ca.crt
|
||||
- --tls-auth-clients
|
||||
- 'no'
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
- .local/redis.acl:/etc/redis.acl:ro
|
||||
- ./.local/id/redis:/identity:ro
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- redis-cli --tls --cacert /identity/ca.crt --sni redis -h redis ping 2>&1 |
|
||||
grep -q NOAUTH
|
||||
interval: 2s
|
||||
timeout: 1s
|
||||
retries: 30
|
||||
cpus: 0.5
|
||||
mem_limit: 192m
|
||||
networks:
|
||||
mesh:
|
||||
aliases:
|
||||
- redis-tls
|
||||
minio:
|
||||
build:
|
||||
context: ./infra/minio
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi5-minio:2025-04-22-local
|
||||
command:
|
||||
- server
|
||||
- --certs-dir
|
||||
- /etc/minio/certs
|
||||
- /data
|
||||
- --console-address
|
||||
- 127.0.0.1:9001
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?}
|
||||
MINIO_API_STALE_UPLOADS_EXPIRY: 24h
|
||||
MINIO_API_STALE_UPLOADS_CLEANUP_INTERVAL: 1h
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
- ./.local/id/minio:/identity:ro
|
||||
- ./.local/id/minio/cert.pem:/etc/minio/certs/public.crt:ro
|
||||
- ./.local/id/minio/key.pem:/etc/minio/certs/private.key:ro
|
||||
- ./.local/id/minio/ca.crt:/etc/minio/certs/CAs/lab.crt:ro
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- curl
|
||||
- -fsS
|
||||
- --cacert
|
||||
- /identity/ca.crt
|
||||
- https://minio:9000/minio/health/live
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 10s
|
||||
cpus: 1.0
|
||||
mem_limit: 768m
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
mesh:
|
||||
aliases:
|
||||
- minio-tls
|
||||
minio-init:
|
||||
image: mtusi5-minio:2025-04-22-local
|
||||
pull_policy: never
|
||||
depends_on:
|
||||
minio:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?}
|
||||
S3_BUCKET: ${S3_BUCKET:?}
|
||||
S3_ACCESS_KEY: ${S3_ACCESS_KEY:?}
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:?}
|
||||
WORKER_S3_PASSWORD: ${WORKER_S3_PASSWORD:?}
|
||||
volumes:
|
||||
- ./infra/minio/bootstrap.sh:/bootstrap/bootstrap.sh:ro
|
||||
- ./.local/ca.crt:/root/.mc/certs/CAs/lab.crt:ro
|
||||
entrypoint:
|
||||
- /bin/sh
|
||||
- /bootstrap/bootstrap.sh
|
||||
restart: 'no'
|
||||
networks:
|
||||
- mesh
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
rabbitmq:
|
||||
image: rabbitmq:4.1.4-alpine
|
||||
hostname: rabbitmq
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
- .local/rabbit.json:/etc/rabbitmq/definitions.json:ro
|
||||
- ./infra/rabbit.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||
- ./.local/id/rabbitmq:/identity:ro
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- rabbitmq-diagnostics
|
||||
- -q
|
||||
- ping
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
start_period: 30s
|
||||
cpus: 1.0
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
mesh:
|
||||
aliases:
|
||||
- rabbitmq-tls
|
||||
environment:
|
||||
RABBITMQ_NODENAME: rabbit@localhost
|
||||
ERL_EPMD_ADDRESS: 127.0.0.1
|
||||
migrate:
|
||||
image: flyway/flyway:10.20.1-alpine
|
||||
command:
|
||||
- -connectRetries=30
|
||||
- migrate
|
||||
environment:
|
||||
FLYWAY_URL: jdbc:postgresql://postgres:5432/messenger?sslmode=verify-full&sslrootcert=/identity/ca.crt
|
||||
FLYWAY_USER: ${POSTGRES_USER:?}
|
||||
FLYWAY_PASSWORD: ${POSTGRES_PASSWORD:?}
|
||||
volumes:
|
||||
- ./java/src/main/resources/db/migration:/flyway/sql:ro
|
||||
- .local/ca.crt:/identity/ca.crt:ro
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
cpus: 0.5
|
||||
mem_limit: 384m
|
||||
restart: 'no'
|
||||
networks:
|
||||
- mesh
|
||||
api:
|
||||
build: .
|
||||
image: messenger7-app:local
|
||||
environment:
|
||||
DB_URL: jdbc:postgresql://postgres:5432/messenger?sslmode=verify-full&sslrootcert=/identity/ca.crt
|
||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-8}
|
||||
REDIS_HOST: 127.0.0.1
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
FLYWAY_ENABLED: 'false'
|
||||
S3_ENDPOINT: http://127.0.0.1:9000
|
||||
S3_BUCKET: ${S3_BUCKET:?}
|
||||
RABBITMQ_HOST: 127.0.0.1
|
||||
WORKER_ENABLED: 'false'
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-3}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-120}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-604800}
|
||||
UPLOAD_MAX_CONCURRENT: ${UPLOAD_MAX_CONCURRENT:-1}
|
||||
UPLOAD_TEMP_DIR: /tmp/messenger-uploads
|
||||
ATTACHMENT_CLEANUP_ENABLED: 'true'
|
||||
ATTACHMENT_CLEANUP_GRACE_SECONDS: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:-3600}
|
||||
ATTACHMENT_CLEANUP_INTERVAL_MS: ${ATTACHMENT_CLEANUP_INTERVAL_MS:-300000}
|
||||
ATTACHMENT_CLEANUP_INITIAL_DELAY_MS: ${ATTACHMENT_CLEANUP_INITIAL_DELAY_MS:-60000}
|
||||
JAVA_TOOL_OPTIONS: -Djava.awt.headless=true
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://127.0.0.1:4318
|
||||
SERVER_ADDRESS: 127.0.0.1
|
||||
SERVICE_ROLE: api
|
||||
SPRING_RABBITMQ_DYNAMIC: 'false'
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
minio-init:
|
||||
condition: service_completed_successfully
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
openbao:
|
||||
condition: service_started
|
||||
otel-collector-tls:
|
||||
condition: service_started
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
cpus: ${API_CPUS:-1.0}
|
||||
mem_limit: ${API_MEMORY:-768m}
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 20s
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- wget
|
||||
- -qO-
|
||||
- http://localhost:8080/health/ready
|
||||
interval: 5s
|
||||
timeout: 15s
|
||||
start_period: 60s
|
||||
retries: 3
|
||||
networks:
|
||||
- mesh
|
||||
volumes:
|
||||
- .local/id/api:/identity:ro
|
||||
- ./infra/tls/api.cfg:/app/transport.cfg:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
worker:
|
||||
image: messenger7-app:local
|
||||
pull_policy: never
|
||||
environment:
|
||||
DB_URL: jdbc:postgresql://postgres:5432/messenger?sslmode=verify-full&sslrootcert=/identity/ca.crt
|
||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-8}
|
||||
REDIS_HOST: 127.0.0.1
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
FLYWAY_ENABLED: 'false'
|
||||
S3_ENDPOINT: http://127.0.0.1:9000
|
||||
S3_BUCKET: ${S3_BUCKET:?}
|
||||
RABBITMQ_HOST: 127.0.0.1
|
||||
WORKER_ENABLED: 'true'
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-3}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-120}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-604800}
|
||||
UPLOAD_MAX_CONCURRENT: ${UPLOAD_MAX_CONCURRENT:-1}
|
||||
UPLOAD_TEMP_DIR: /tmp/messenger-uploads
|
||||
ATTACHMENT_CLEANUP_ENABLED: 'false'
|
||||
ATTACHMENT_CLEANUP_GRACE_SECONDS: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:-3600}
|
||||
ATTACHMENT_CLEANUP_INTERVAL_MS: ${ATTACHMENT_CLEANUP_INTERVAL_MS:-300000}
|
||||
ATTACHMENT_CLEANUP_INITIAL_DELAY_MS: ${ATTACHMENT_CLEANUP_INITIAL_DELAY_MS:-60000}
|
||||
JAVA_TOOL_OPTIONS: -Djava.awt.headless=true
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://127.0.0.1:4318
|
||||
SERVER_ADDRESS: 127.0.0.1
|
||||
SERVICE_ROLE: worker
|
||||
SPRING_RABBITMQ_DYNAMIC: 'false'
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
minio-init:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
openbao:
|
||||
condition: service_started
|
||||
otel-collector-tls:
|
||||
condition: service_started
|
||||
cpus: 1.0
|
||||
mem_limit: 768m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 20s
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- wget
|
||||
- -qO-
|
||||
- http://localhost:8080/health/live
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
start_period: 60s
|
||||
retries: 10
|
||||
networks:
|
||||
- mesh
|
||||
volumes:
|
||||
- .local/id/worker:/identity:ro
|
||||
- ./infra/tls/worker.cfg:/app/transport.cfg:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
lb:
|
||||
image: nginx:1.28-alpine
|
||||
ports:
|
||||
- 127.0.0.1:8443:8443
|
||||
networks:
|
||||
- edge
|
||||
- mesh
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
mem_limit: 96m
|
||||
cpus: 0.5
|
||||
volumes:
|
||||
- .local/id/lb:/identity:ro
|
||||
- ./infra/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.115.1
|
||||
command:
|
||||
- --config=/etc/otelcol/config.yaml
|
||||
volumes:
|
||||
- ./infra/observability/collector.yaml:/etc/otelcol/config.yaml:ro
|
||||
- ./.local/id/otel-collector:/identity:ro
|
||||
networks:
|
||||
local-otel-collector:
|
||||
ipv4_address: 172.29.123.3
|
||||
mem_limit: 256m
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- loki
|
||||
- tempo
|
||||
cpus: 0.5
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.0.1
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yaml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=7d
|
||||
volumes:
|
||||
- ./infra/observability/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||
- prometheus_data:/prometheus
|
||||
networks:
|
||||
local-prometheus:
|
||||
ipv4_address: 172.29.124.3
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
cpus: 0.5
|
||||
loki:
|
||||
image: grafana/loki:3.3.2
|
||||
command:
|
||||
- -config.file=/etc/loki/config.yaml
|
||||
volumes:
|
||||
- ./infra/observability/loki.yaml:/etc/loki/config.yaml:ro
|
||||
- loki_data:/loki
|
||||
networks:
|
||||
local-loki:
|
||||
ipv4_address: 172.29.125.3
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
cpus: 0.5
|
||||
tempo:
|
||||
image: grafana/tempo:2.6.1
|
||||
user: 0:0
|
||||
command:
|
||||
- -config.file=/etc/tempo/config.yaml
|
||||
volumes:
|
||||
- ./infra/observability/tempo.yaml:/etc/tempo/config.yaml:ro
|
||||
- tempo_data:/var/tempo
|
||||
networks:
|
||||
local-tempo:
|
||||
ipv4_address: 172.29.126.3
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
cpus: 0.5
|
||||
grafana:
|
||||
image: grafana/grafana:11.4.0
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: ${GRAFANA_USER:-admin}
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:?}
|
||||
GF_USERS_ALLOW_SIGN_UP: 'false'
|
||||
GF_ANALYTICS_REPORTING_ENABLED: 'false'
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
|
||||
volumes:
|
||||
- grafana_data:/var/lib/grafana
|
||||
- ./infra/observability/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/observability/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
networks:
|
||||
local-grafana:
|
||||
ipv4_address: 172.29.127.3
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- prometheus
|
||||
- loki
|
||||
- tempo
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- wget -qO- http://localhost:3000/api/health >/dev/null
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
cpus: 0.5
|
||||
otel-collector-tls:
|
||||
image: haproxy:3.0.5-alpine
|
||||
user: 65534:65534
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 64m
|
||||
cpus: 0.25
|
||||
networks:
|
||||
local-otel-collector:
|
||||
ipv4_address: 172.29.123.2
|
||||
aliases:
|
||||
- transport
|
||||
mesh:
|
||||
aliases:
|
||||
- collector-egress
|
||||
volumes:
|
||||
- ./infra/tls/otel-collector.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- .local/id/otel-collector:/identity:ro
|
||||
prometheus-tls:
|
||||
image: haproxy:3.0.5-alpine
|
||||
user: 65534:65534
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 64m
|
||||
cpus: 0.25
|
||||
networks:
|
||||
mesh: {}
|
||||
local-prometheus:
|
||||
ipv4_address: 172.29.124.2
|
||||
aliases:
|
||||
- transport
|
||||
volumes:
|
||||
- ./infra/tls/prometheus.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- .local/id/prometheus:/identity:ro
|
||||
loki-tls:
|
||||
image: haproxy:3.0.5-alpine
|
||||
user: 65534:65534
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 64m
|
||||
cpus: 0.25
|
||||
networks:
|
||||
mesh: {}
|
||||
local-loki:
|
||||
ipv4_address: 172.29.125.2
|
||||
aliases:
|
||||
- transport
|
||||
volumes:
|
||||
- ./infra/tls/loki.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- .local/id/loki:/identity:ro
|
||||
tempo-tls:
|
||||
image: haproxy:3.0.5-alpine
|
||||
user: 65534:65534
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 64m
|
||||
cpus: 0.25
|
||||
networks:
|
||||
mesh: {}
|
||||
local-tempo:
|
||||
ipv4_address: 172.29.126.2
|
||||
aliases:
|
||||
- transport
|
||||
volumes:
|
||||
- ./infra/tls/tempo.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- .local/id/tempo:/identity:ro
|
||||
grafana-tls:
|
||||
image: haproxy:3.0.5-alpine
|
||||
user: 65534:65534
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 64m
|
||||
cpus: 0.25
|
||||
networks:
|
||||
mesh: {}
|
||||
local-grafana:
|
||||
ipv4_address: 172.29.127.2
|
||||
aliases:
|
||||
- transport
|
||||
edge: {}
|
||||
volumes:
|
||||
- ./infra/tls/grafana.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- .local/id/grafana:/identity:ro
|
||||
ports:
|
||||
- 127.0.0.1:3443:3443
|
||||
openbao:
|
||||
image: quay.io/openbao/openbao:2.4.4
|
||||
command:
|
||||
- server
|
||||
- -config=/config/server.hcl
|
||||
environment:
|
||||
BAO_ADDR: https://localhost:8200
|
||||
BAO_CACERT: /identity/ca.crt
|
||||
SKIP_SETCAP: 'true'
|
||||
networks:
|
||||
- edge
|
||||
- mesh
|
||||
ports:
|
||||
- 127.0.0.1:8200:8200
|
||||
volumes:
|
||||
- bao_data:/openbao/file
|
||||
- .local/id/openbao:/identity:ro
|
||||
- ./infra/openbao/server.hcl:/config/server.hcl:ro
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
probe:
|
||||
profiles:
|
||||
- checks
|
||||
image: messenger7-app:local
|
||||
entrypoint:
|
||||
- python3
|
||||
- /checks/internal_tls.py
|
||||
networks:
|
||||
- mesh
|
||||
volumes:
|
||||
- ./tests/internal_tls.py:/checks/internal_tls.py:ro
|
||||
- ./.local/ca.crt:/probe/ca.crt:ro
|
||||
- ./.local/id/lb:/probe/lb:ro
|
||||
- ./.local/id/api:/probe/api:ro
|
||||
- ./.local/id/worker:/probe/worker:ro
|
||||
- ./.local/id/foreign:/probe/foreign:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
mem_limit: 96m
|
||||
cpus: 0.25
|
||||
volumes:
|
||||
postgres_data: null
|
||||
redis_data: null
|
||||
minio_data: null
|
||||
rabbitmq_data: null
|
||||
prometheus_data: null
|
||||
loki_data: null
|
||||
tempo_data: null
|
||||
grafana_data: null
|
||||
bao_data: null
|
||||
networks:
|
||||
mesh:
|
||||
internal: true
|
||||
edge: {}
|
||||
local-otel-collector:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.29.123.0/28
|
||||
local-prometheus:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.29.124.0/28
|
||||
local-loki:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.29.125.0/28
|
||||
local-tempo:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.29.126.0/28
|
||||
local-grafana:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.29.127.0/28
|
||||
name: messenger7
|
||||
@@ -0,0 +1,78 @@
|
||||
Docker Compose version v5.5.1
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
messenger7-api-1 messenger7-app:local "python3 /app/start.…" api 21 minutes ago Up 17 minutes (healthy) 8080/tcp
|
||||
messenger7-api-2 messenger7-app:local "python3 /app/start.…" api 21 minutes ago Up 17 minutes (healthy) 8080/tcp
|
||||
messenger7-grafana-1 grafana/grafana:11.4.0 "/run.sh" grafana 18 minutes ago Up 17 minutes (healthy) 3000/tcp
|
||||
messenger7-grafana-tls-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" grafana-tls 18 minutes ago Up 18 minutes 127.0.0.1:3443->3443/tcp
|
||||
messenger7-lb-1 nginx:1.28-alpine "/docker-entrypoint.…" lb 21 minutes ago Up 17 minutes 127.0.0.1:8443->8443/tcp
|
||||
messenger7-loki-1 grafana/loki:3.3.2 "/usr/bin/loki -conf…" loki 18 minutes ago Up 18 minutes 3100/tcp
|
||||
messenger7-loki-tls-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" loki-tls 18 minutes ago Up 18 minutes
|
||||
messenger7-minio-1 mtusi5-minio:2025-04-22-local "minio server --cert…" minio 21 minutes ago Up 21 minutes (healthy) 9000-9001/tcp
|
||||
messenger7-openbao-1 quay.io/openbao/openbao:2.4.4 "docker-entrypoint.s…" openbao About an hour ago Up About an hour 127.0.0.1:8200->8200/tcp
|
||||
messenger7-otel-collector-1 otel/opentelemetry-collector-contrib:0.115.1 "/otelcol-contrib --…" otel-collector 18 minutes ago Up 18 minutes 4317-4318/tcp, 55678-55679/tcp
|
||||
messenger7-otel-collector-tls-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" otel-collector-tls 18 minutes ago Up 18 minutes
|
||||
messenger7-postgres-1 postgres:16.6-alpine "/bin/sh -ec 'instal…" postgres 21 minutes ago Up 21 minutes (healthy) 5432/tcp
|
||||
messenger7-prometheus-1 prom/prometheus:v3.0.1 "/bin/prometheus --c…" prometheus 18 minutes ago Up 18 minutes 9090/tcp
|
||||
messenger7-prometheus-tls-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" prometheus-tls 18 minutes ago Up 18 minutes
|
||||
messenger7-rabbitmq-1 rabbitmq:4.1.4-alpine "docker-entrypoint.s…" rabbitmq 21 minutes ago Up 21 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||
messenger7-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 10 minutes ago Up 10 minutes (healthy) 6379/tcp
|
||||
messenger7-tempo-1 grafana/tempo:2.6.1 "/tempo -config.file…" tempo 18 minutes ago Up 18 minutes
|
||||
messenger7-tempo-tls-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" tempo-tls 13 minutes ago Up 13 minutes
|
||||
messenger7-worker-1 messenger7-app:local "python3 /app/start.…" worker 21 minutes ago Up 17 minutes (healthy) 8080/tcp
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
python3 scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file ".local/ca.crt"
|
||||
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||
python3 tests/security.py --base-url "https://localhost:8443" --ca-file ".local/ca.crt"
|
||||
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||
docker compose exec -T api java -XX:MaxRAMPercentage=25 -Dloader.main=com.vnp.demo.config.PasswordBenchmark -cp /app/app.jar org.springframework.boot.loader.launch.PropertiesLauncher
|
||||
Picked up JAVA_TOOL_OPTIONS: -Djava.awt.headless=true
|
||||
Argon2id m=19456 KiB t=2 p=1 n=25 verify p50=31 ms p95=138 ms
|
||||
python3 tests/resilience.py --mode persistence --action-script "./scripts/restart.sh" --base-url "https://localhost:8443" --ca-file ".local/ca.crt"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
python3 tests/resilience.py --mode failover --action-script "./scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file ".local/ca.crt"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 116, "failed_attempts": 0, "first_recovery_seconds": 0.66}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
Container messenger7-api-2 Running
|
||||
Container messenger7-api-1 Starting
|
||||
Container messenger7-api-1 Started
|
||||
Container messenger7-api-2 Waiting
|
||||
Container messenger7-api-1 Waiting
|
||||
Container messenger7-api-2 Healthy
|
||||
Container messenger7-api-1 Healthy
|
||||
Container messenger7-api-2 Recreate
|
||||
Container messenger7-api-1 Recreate
|
||||
Container messenger7-api-2 Recreated
|
||||
Container messenger7-api-1 Recreated
|
||||
Container messenger7-api-1 Starting
|
||||
Container messenger7-api-1 Started
|
||||
Container messenger7-api-2 Starting
|
||||
Container messenger7-api-2 Started
|
||||
Container messenger7-api-1 Waiting
|
||||
Container messenger7-api-2 Waiting
|
||||
Container messenger7-api-1 Healthy
|
||||
Container messenger7-api-2 Healthy
|
||||
PASS: a previously accepted bearer expired
|
||||
Container messenger7-api-1 Recreate
|
||||
Container messenger7-api-2 Recreate
|
||||
Container messenger7-api-1 Recreated
|
||||
Container messenger7-api-2 Recreated
|
||||
Container messenger7-api-1 Starting
|
||||
Container messenger7-api-1 Started
|
||||
Container messenger7-api-2 Starting
|
||||
Container messenger7-api-2 Started
|
||||
Container messenger7-api-1 Waiting
|
||||
Container messenger7-api-2 Waiting
|
||||
Container messenger7-api-1 Healthy
|
||||
Container messenger7-api-2 Healthy
|
||||
python3 tests/negative_api.py --base-url "https://localhost:8443" --ca-file ".local/ca.crt"
|
||||
PASS: hostname, foreign attachment and ingress rate limit
|
||||
docker compose run --rm --no-deps probe
|
||||
Container messenger7-probe-run-4145f02adc6b Creating
|
||||
Container messenger7-probe-run-4145f02adc6b Created
|
||||
PASS: all 2 API replicas accepted LB and rejected three invalid clients
|
||||
PASS: scoped KV, denied policy mutation and token revocation for both roles
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Fetch the role's KV record before starting any business listener."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import urllib.request
|
||||
|
||||
role = os.environ['SERVICE_ROLE']
|
||||
ctx = ssl.create_default_context(cafile='/identity/ca.crt')
|
||||
ctx.load_cert_chain('/identity/cert.pem', '/identity/key.pem')
|
||||
|
||||
def bao(path, data=None, token=None):
|
||||
req = urllib.request.Request('https://openbao:8200/v1/' + path,
|
||||
data=json.dumps(data).encode() if data is not None else None,
|
||||
headers={'X-Vault-Token': token} if token else {})
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=8) as res:
|
||||
return json.load(res)
|
||||
|
||||
token = bao('auth/cert/login', {'name': role})['auth']['client_token']
|
||||
values = bao('messenger/data/' + role, token=token)['data']['data']
|
||||
keys = {'DB_USERNAME','DB_PASSWORD','S3_ACCESS_KEY','S3_SECRET_KEY','RABBITMQ_USER','RABBITMQ_PASSWORD'}
|
||||
if role == 'api':
|
||||
keys.update({'REDIS_PASSWORD','SPRING_DATA_REDIS_USERNAME'})
|
||||
if set(values) != keys:
|
||||
raise RuntimeError('Unexpected OpenBao record schema')
|
||||
os.environ.update(values)
|
||||
subprocess.run(['haproxy','-D','-f','/app/transport.cfg'],check=True)
|
||||
os.execvp('java',['java','-XX:MaxRAMPercentage=75','-jar','/app/app.jar'])
|
||||
@@ -0,0 +1,176 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
|
||||
from PIL import Image, ImageFile, ImageOps, UnidentifiedImageError
|
||||
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
|
||||
|
||||
def fit_size(width, height, bound):
|
||||
denominator = max(bound, width, height)
|
||||
|
||||
return (
|
||||
max(1, width * bound // denominator),
|
||||
max(1, height * bound // denominator),
|
||||
)
|
||||
|
||||
|
||||
def white_rgb(image):
|
||||
rgba = image.convert("RGBA")
|
||||
output = Image.new("RGB", rgba.size, "white")
|
||||
|
||||
output.paste(
|
||||
rgba,
|
||||
mask=rgba.getchannel("A"),
|
||||
)
|
||||
|
||||
rgba.close()
|
||||
return output
|
||||
|
||||
|
||||
def main():
|
||||
# Ограничения дочернего процесса Linux.
|
||||
resource.setrlimit(
|
||||
resource.RLIMIT_AS,
|
||||
(768 * 1024**2,) * 2,
|
||||
)
|
||||
|
||||
resource.setrlimit(
|
||||
resource.RLIMIT_CPU,
|
||||
(20, 21),
|
||||
)
|
||||
|
||||
resource.setrlimit(
|
||||
resource.RLIMIT_FSIZE,
|
||||
(11 * 1024**2,) * 2,
|
||||
)
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
warnings.simplefilter(
|
||||
"error",
|
||||
Image.DecompressionBombWarning,
|
||||
)
|
||||
|
||||
source, output = map(Path, sys.argv[1:3])
|
||||
|
||||
if not 0 < source.stat().st_size <= MAX_BYTES:
|
||||
return 10
|
||||
|
||||
if os.environ.get("IMAGE_TEST_SLEEP") == "1":
|
||||
time.sleep(60)
|
||||
|
||||
try:
|
||||
image = Image.open(source)
|
||||
|
||||
if (
|
||||
image.format not in ("PNG", "JPEG")
|
||||
or image.width * image.height > MAX_PIXELS
|
||||
):
|
||||
image.close()
|
||||
return 10
|
||||
|
||||
image.load()
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
|
||||
except (
|
||||
ValueError,
|
||||
UnidentifiedImageError,
|
||||
OSError,
|
||||
SyntaxError,
|
||||
Image.DecompressionBombWarning,
|
||||
Image.DecompressionBombError,
|
||||
):
|
||||
return 10
|
||||
|
||||
with image:
|
||||
manifest = []
|
||||
|
||||
variants = [
|
||||
("thumbnail", 256, "image/jpeg", "jpg"),
|
||||
("crop", 128, "image/jpeg", "jpg"),
|
||||
("optimized", 1280, "image/webp", "webp"),
|
||||
]
|
||||
|
||||
for name, bound, mime, extension in variants:
|
||||
if name == "crop":
|
||||
scaled = ImageOps.fit(
|
||||
image,
|
||||
(128, 128),
|
||||
method=Image.Resampling.LANCZOS,
|
||||
centering=(0.5, 0.5),
|
||||
)
|
||||
else:
|
||||
scaled = image.resize(
|
||||
fit_size(*image.size, bound),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
|
||||
if extension == "jpg":
|
||||
rendered = white_rgb(scaled)
|
||||
else:
|
||||
rendered = scaled.convert("RGBA")
|
||||
|
||||
scaled.close()
|
||||
|
||||
rendered.info.clear()
|
||||
|
||||
path = output / (name + "." + extension)
|
||||
|
||||
if extension == "jpg":
|
||||
rendered.save(
|
||||
path,
|
||||
"JPEG",
|
||||
quality=85,
|
||||
subsampling=2,
|
||||
optimize=True,
|
||||
exif=b"",
|
||||
icc_profile=None,
|
||||
)
|
||||
else:
|
||||
rendered.save(
|
||||
path,
|
||||
"WEBP",
|
||||
quality=80,
|
||||
method=4,
|
||||
lossless=False,
|
||||
exif=b"",
|
||||
icc_profile=b"",
|
||||
xmp=b"",
|
||||
)
|
||||
|
||||
manifest.append(
|
||||
{
|
||||
"name": name,
|
||||
"content_type": mime,
|
||||
"width": rendered.width,
|
||||
"height": rendered.height,
|
||||
}
|
||||
)
|
||||
|
||||
rendered.close()
|
||||
|
||||
if not 0 < path.stat().st_size <= MAX_BYTES:
|
||||
return 11
|
||||
|
||||
(output / "manifest.json").write_text(
|
||||
json.dumps(manifest),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (MemoryError, OSError):
|
||||
sys.exit(11)
|
||||
@@ -0,0 +1,184 @@
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).with_name("process_image.py")
|
||||
|
||||
|
||||
def execute(folder, expected):
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(SCRIPT),
|
||||
str(folder / "input.bin"),
|
||||
str(folder),
|
||||
],
|
||||
capture_output=True,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
assert result.returncode == expected, (
|
||||
folder.name,
|
||||
result.returncode,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
|
||||
cases = [
|
||||
(
|
||||
"alpha",
|
||||
(320, 200),
|
||||
"RGBA",
|
||||
(255, 0, 0, 0),
|
||||
None,
|
||||
[(256, 160), (128, 128), (320, 200)],
|
||||
),
|
||||
(
|
||||
"small",
|
||||
(20, 10),
|
||||
"RGB",
|
||||
"red",
|
||||
None,
|
||||
[(20, 10), (128, 128), (20, 10)],
|
||||
),
|
||||
(
|
||||
"orientation",
|
||||
(320, 200),
|
||||
"RGB",
|
||||
"blue",
|
||||
6,
|
||||
[(160, 256), (128, 128), (200, 320)],
|
||||
),
|
||||
]
|
||||
|
||||
for label, size, mode, color, orientation, expected in cases:
|
||||
folder = root / label
|
||||
folder.mkdir()
|
||||
|
||||
with Image.new(mode, size, color) as image:
|
||||
if orientation:
|
||||
exif = Image.Exif()
|
||||
exif[274] = orientation
|
||||
|
||||
image.save(
|
||||
folder / "input.bin",
|
||||
"JPEG",
|
||||
exif=exif,
|
||||
)
|
||||
else:
|
||||
image.save(folder / "input.bin", "PNG")
|
||||
|
||||
execute(folder, 0)
|
||||
|
||||
names = [
|
||||
"thumbnail.jpg",
|
||||
"crop.jpg",
|
||||
"optimized.webp",
|
||||
]
|
||||
|
||||
for name, dimensions in zip(names, expected):
|
||||
with Image.open(folder / name) as result:
|
||||
assert result.size == dimensions
|
||||
assert not result.getexif()
|
||||
|
||||
assert not any(
|
||||
result.info.get(key)
|
||||
for key in ["icc_profile", "xmp", "exif"]
|
||||
)
|
||||
|
||||
if label == "alpha" and name.endswith(".jpg"):
|
||||
assert result.getpixel((0, 0)) == (
|
||||
255,
|
||||
255,
|
||||
255,
|
||||
)
|
||||
|
||||
print("PASS:", label)
|
||||
|
||||
folder = root / "center_crop"
|
||||
folder.mkdir()
|
||||
|
||||
with Image.new("RGB", (400, 200), "blue") as image:
|
||||
image.paste("red", (0, 0, 100, 200))
|
||||
image.paste("green", (300, 0, 400, 200))
|
||||
image.save(folder / "input.bin", "PNG")
|
||||
|
||||
execute(folder, 0)
|
||||
|
||||
with Image.open(folder / "crop.jpg") as crop:
|
||||
for x in [32, 96]:
|
||||
red, green, blue = crop.getpixel((x, 64))
|
||||
|
||||
assert blue > 240
|
||||
assert red < 15
|
||||
assert green < 15
|
||||
|
||||
print("PASS: centered crop")
|
||||
|
||||
for label, data in [
|
||||
("broken", b"not an image"),
|
||||
("bytes_limit", b"x" * (10485760 + 1)),
|
||||
]:
|
||||
folder = root / label
|
||||
folder.mkdir()
|
||||
|
||||
(folder / "input.bin").write_bytes(data)
|
||||
|
||||
execute(folder, 10)
|
||||
|
||||
print("PASS rejected:", label)
|
||||
|
||||
folder = root / "pixels"
|
||||
folder.mkdir()
|
||||
|
||||
def chunk(kind, data):
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ kind
|
||||
+ data
|
||||
+ struct.pack(
|
||||
">I",
|
||||
zlib.crc32(kind + data) & 0xffffffff,
|
||||
)
|
||||
)
|
||||
|
||||
png = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(
|
||||
b"IHDR",
|
||||
struct.pack(
|
||||
">IIBBBBB",
|
||||
10000,
|
||||
10000,
|
||||
8,
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
)
|
||||
+ chunk(
|
||||
b"IDAT",
|
||||
zlib.compress(b"\0\0\0\0"),
|
||||
)
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
(folder / "input.bin").write_bytes(png)
|
||||
|
||||
execute(folder, 10)
|
||||
|
||||
print("PASS rejected: pixels before decode")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
FROM golang:1.24.2-bookworm AS builder
|
||||
|
||||
ENV CGO_ENABLED=0
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
RUN git clone --depth 1 \
|
||||
--branch RELEASE.2025-04-22T22-12-26Z \
|
||||
https://github.com/minio/minio.git /src/minio
|
||||
|
||||
WORKDIR /src/minio
|
||||
|
||||
RUN go build -trimpath -o /out/minio .
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
RUN git clone --depth 1 \
|
||||
--branch RELEASE.2025-04-16T18-13-26Z \
|
||||
https://github.com/minio/mc.git /src/mc
|
||||
|
||||
WORKDIR /src/mc
|
||||
|
||||
RUN go build -trimpath -o /out/mc .
|
||||
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=builder /out/minio /usr/local/bin/minio
|
||||
COPY --from=builder /out/mc /usr/local/bin/mc
|
||||
|
||||
RUN mkdir -p /data
|
||||
|
||||
EXPOSE 9000 9001
|
||||
|
||||
ENTRYPOINT ["minio"]
|
||||
CMD ["server", "/data", "--console-address", ":9001"]
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${MINIO_ROOT_USER:?}"
|
||||
: "${MINIO_ROOT_PASSWORD:?}"
|
||||
: "${S3_BUCKET:?}"
|
||||
: "${S3_ACCESS_KEY:?}"
|
||||
: "${S3_SECRET_KEY:?}"
|
||||
|
||||
if [ "$S3_ACCESS_KEY" = "$MINIO_ROOT_USER" ]; then
|
||||
echo "API must use a separate MinIO user" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$S3_SECRET_KEY" = "$MINIO_ROOT_PASSWORD" ]; then
|
||||
echo "API and administrator passwords must differ" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$S3_BUCKET" in
|
||||
""|*[!a-z0-9.-]*)
|
||||
echo "Invalid bucket name" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
mc alias set storage https://minio:9000 \
|
||||
"$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null
|
||||
|
||||
mc mb --ignore-existing "storage/$S3_BUCKET"
|
||||
mc anonymous set none "storage/$S3_BUCKET"
|
||||
|
||||
for role in api worker; do
|
||||
user="messenger_$role"
|
||||
if [ "$role" = api ]; then
|
||||
password="$S3_SECRET_KEY"
|
||||
write_prefix=staging
|
||||
else
|
||||
password="$WORKER_S3_PASSWORD"
|
||||
write_prefix=originals
|
||||
fi
|
||||
read_actions='"s3:GetObject"'
|
||||
if [ "$role" = api ]; then read_actions='"s3:GetObject","s3:DeleteObject"'; fi
|
||||
extra=""
|
||||
if [ "$role" = worker ]; then
|
||||
extra=',"arn:aws:s3:::'"$S3_BUCKET"'/variants/*"'
|
||||
fi
|
||||
cat > /tmp/policy.json <<EOF
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:GetBucketLocation","s3:ListBucket"],"Resource":["arn:aws:s3:::$S3_BUCKET"]},
|
||||
{"Effect":"Allow","Action":[$read_actions],"Resource":["arn:aws:s3:::$S3_BUCKET/originals/*","arn:aws:s3:::$S3_BUCKET/variants/*","arn:aws:s3:::$S3_BUCKET/staging/*"]},
|
||||
{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::$S3_BUCKET/$write_prefix/*"$extra]}]}
|
||||
EOF
|
||||
policy="messenger-$role"
|
||||
mc admin policy create storage "$policy" /tmp/policy.json >/dev/null
|
||||
mc admin user add storage "$user" "$password" >/dev/null
|
||||
if ! mc admin user info --json storage "$user" | grep -Eq '"policyName"[[:space:]]*:[[:space:]]*"'"$policy"'"'; then
|
||||
mc admin policy attach storage "$policy" --user "$user" >/dev/null
|
||||
fi
|
||||
done
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${S3_BUCKET:?}"
|
||||
: "${S3_ACCESS_KEY:?}"
|
||||
: "${S3_SECRET_KEY:?}"
|
||||
|
||||
mc alias set app http://minio:9000 \
|
||||
"$S3_ACCESS_KEY" "$S3_SECRET_KEY" >/dev/null
|
||||
|
||||
TEST_ID="$(cat /proc/sys/kernel/random/uuid)"
|
||||
OBJECT_KEY="originals/access-check-$TEST_ID.txt"
|
||||
OUTSIDE_KEY="outside-access-check-$TEST_ID.txt"
|
||||
|
||||
cleanup() {
|
||||
mc rm --force \
|
||||
"app/$S3_BUCKET/$OBJECT_KEY" >/dev/null 2>&1 || true
|
||||
|
||||
mc rm --force \
|
||||
"app/$S3_BUCKET/$OUTSIDE_KEY" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
|
||||
printf 'private attachment test' > /tmp/expected.txt
|
||||
|
||||
mc cp /tmp/expected.txt \
|
||||
"app/$S3_BUCKET/$OBJECT_KEY" >/dev/null
|
||||
|
||||
mc cat "app/$S3_BUCKET/$OBJECT_KEY" > /tmp/actual.txt
|
||||
|
||||
cmp /tmp/expected.txt /tmp/actual.txt
|
||||
|
||||
echo "PASS: API credentials can upload and download originals"
|
||||
|
||||
HTTP_CODE="$(
|
||||
curl --silent --show-error \
|
||||
--connect-timeout 3 \
|
||||
--max-time 10 \
|
||||
--output /tmp/anonymous-response.xml \
|
||||
--write-out '%{http_code}' \
|
||||
"http://minio:9000/$S3_BUCKET/$OBJECT_KEY"
|
||||
)"
|
||||
|
||||
if [ "$HTTP_CODE" != "403" ]; then
|
||||
echo "FAIL: anonymous GET returned HTTP $HTTP_CODE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -q '<Code>AccessDenied</Code>' \
|
||||
/tmp/anonymous-response.xml
|
||||
then
|
||||
echo "FAIL: expected S3 AccessDenied response" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: anonymous download of an existing object is denied"
|
||||
|
||||
if mc cp /tmp/expected.txt \
|
||||
"app/$S3_BUCKET/$OUTSIDE_KEY" \
|
||||
> /tmp/outside-result.txt 2>&1
|
||||
then
|
||||
echo "FAIL: API credentials can write outside originals/" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -Eiq \
|
||||
'AccessDenied|Access Denied|Insufficient permissions|not authorized|not allowed' \
|
||||
/tmp/outside-result.txt
|
||||
then
|
||||
echo "FAIL: write failed for a reason other than access denial" >&2
|
||||
cat /tmp/outside-result.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: writing outside originals/ is denied"
|
||||
|
||||
if mc admin info app > /tmp/admin-result.txt 2>&1
|
||||
then
|
||||
echo "FAIL: API credentials have administrative access" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -Eiq \
|
||||
'AccessDenied|Access Denied|Insufficient permissions|not authorized|not allowed' \
|
||||
/tmp/admin-result.txt
|
||||
then
|
||||
echo "FAIL: admin command failed for an unexpected reason" >&2
|
||||
cat /tmp/admin-result.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: administrative access is denied"
|
||||
|
||||
mc rm "app/$S3_BUCKET/$OBJECT_KEY" >/dev/null
|
||||
|
||||
echo "PASS: API credentials can delete originals for cleanup"
|
||||
echo "PASS: S3 access checks completed"
|
||||
@@ -0,0 +1,51 @@
|
||||
worker_processes 1;
|
||||
events { worker_connections 1024; }
|
||||
http {
|
||||
access_log off;
|
||||
resolver 127.0.0.11 valid=2s ipv6=off;
|
||||
upstream messenger {
|
||||
zone replicas 64k;
|
||||
server api:8443 resolve max_fails=1 fail_timeout=2s;
|
||||
}
|
||||
map "$request_method:$uri" $login_key {
|
||||
default "";
|
||||
"POST:/api/v1/auth/sessions" $binary_remote_addr;
|
||||
}
|
||||
limit_req_zone $login_key zone=login:1m rate=1r/s;
|
||||
server {
|
||||
listen 8443 ssl;
|
||||
ssl_certificate /identity/cert.pem;
|
||||
ssl_certificate_key /identity/key.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
client_max_body_size 10m;
|
||||
limit_req zone=login burst=15 nodelay;
|
||||
limit_req_status 429;
|
||||
error_page 429 = @rate;
|
||||
error_page 413 = @large;
|
||||
location @rate {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header X-Instance-Id ingress always;
|
||||
add_header Retry-After 1 always;
|
||||
return 429 '{"error":{"code":"rate_limited","message":"Login limit","request_id":"$request_id"}}';
|
||||
}
|
||||
location @large {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header X-Instance-Id ingress always;
|
||||
return 413 '{"error":{"code":"payload_too_large","message":"Body exceeds limit","request_id":"$request_id"}}';
|
||||
}
|
||||
location /actuator { return 404; }
|
||||
location / {
|
||||
proxy_pass https://messenger;
|
||||
proxy_ssl_certificate /identity/cert.pem;
|
||||
proxy_ssl_certificate_key /identity/key.pem;
|
||||
proxy_ssl_trusted_certificate /identity/ca.crt;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name api;
|
||||
proxy_set_header X-User-Id "";
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 48
|
||||
batch:
|
||||
timeout: 2s
|
||||
send_batch_size: 256
|
||||
send_batch_max_size: 512
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
otlp/tempo:
|
||||
endpoint: transport:4317
|
||||
tls:
|
||||
insecure: true
|
||||
sending_queue:
|
||||
queue_size: 256
|
||||
retry_on_failure:
|
||||
max_elapsed_time: 60s
|
||||
otlphttp/loki:
|
||||
endpoint: http://transport:3100/otlp
|
||||
sending_queue:
|
||||
queue_size: 256
|
||||
retry_on_failure:
|
||||
max_elapsed_time: 60s
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
service:
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,326 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Messenger — Lab 6",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"editable": true,
|
||||
"refresh": "5s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"tags": [
|
||||
"lab6",
|
||||
"otel"
|
||||
],
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"name": "trace_id",
|
||||
"label": "X-Trace-Id",
|
||||
"type": "textbox",
|
||||
"current": {
|
||||
"text": "",
|
||||
"value": ""
|
||||
},
|
||||
"options": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "API — RPS (без health)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(messenger_http_requests_total{service_name=\"messenger-api\"}[1m]))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "API — 5xx / все запросы",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",status_class=\"5xx\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name=\"messenger-api\"}[1m])), 0.000001)",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "API — p95 по всем репликам",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "API — RPS по route / status",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (route,status_class) (rate(messenger_http_requests_total{service_name=\"messenger-api\"}[1m]))",
|
||||
"legendFormat": "{{route}} {{status_class}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Worker — успешные / ошибочные / пропущенные доставки",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (increase(messenger_jobs_total{service_name=\"messenger-worker\"}[5m]))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Worker — p95 processing duration",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le,outcome) (rate(messenger_job_duration_seconds_bucket{service_name=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "API — структурные логи",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-api\"}",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": ""
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"showTime": true,
|
||||
"showLabels": false,
|
||||
"wrapLogMessage": true,
|
||||
"sortOrder": "Descending"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Worker — структурные логи",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-worker\"}",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": ""
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"showTime": true,
|
||||
"showLabels": false,
|
||||
"wrapLogMessage": true,
|
||||
"sortOrder": "Descending"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Трасса по X-Trace-Id",
|
||||
"type": "traces",
|
||||
"datasource": {
|
||||
"type": "tempo",
|
||||
"uid": "tempo"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 24,
|
||||
"h": 10
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"queryType": "traceId",
|
||||
"query": "${trace_id}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: Messenger
|
||||
folder: Lab 6
|
||||
type: file
|
||||
disableDeletion: true
|
||||
updateIntervalSeconds: 10
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,37 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://transport:9090
|
||||
isDefault: true
|
||||
jsonData:
|
||||
timeInterval: 5s
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://transport:3100
|
||||
jsonData:
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
urlDisplayLabel: Open trace
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://transport:3200
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-1m'
|
||||
spanEndTimeShift: '1m'
|
||||
filterByTraceID: false
|
||||
filterBySpanID: false
|
||||
customQuery: true
|
||||
query: '{service_name=~"messenger-api|messenger-worker"} | trace_id="$${__trace.traceId}"'
|
||||
@@ -0,0 +1,32 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
common:
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
instance_addr: 127.0.0.1
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 168h
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,6 @@
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
scrape_configs:
|
||||
- job_name: messenger-otel
|
||||
static_configs:
|
||||
- targets: ['transport:8889']
|
||||
@@ -0,0 +1,24 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
ingester:
|
||||
max_block_duration: 5m
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,15 @@
|
||||
disable_mlock = true
|
||||
storage "raft" {
|
||||
path = "/openbao/file"
|
||||
node_id = "messenger-bao"
|
||||
}
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
cluster_address = "127.0.0.1:8201"
|
||||
tls_cert_file = "/identity/cert.pem"
|
||||
tls_key_file = "/identity/key.pem"
|
||||
tls_client_ca_file = "/identity/ca.crt"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
api_addr = "https://openbao:8200"
|
||||
cluster_addr = "https://127.0.0.1:8201"
|
||||
@@ -0,0 +1,176 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
|
||||
from PIL import Image, ImageFile, ImageOps, UnidentifiedImageError
|
||||
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
|
||||
|
||||
def fit_size(width, height, bound):
|
||||
denominator = max(bound, width, height)
|
||||
|
||||
return (
|
||||
max(1, width * bound // denominator),
|
||||
max(1, height * bound // denominator),
|
||||
)
|
||||
|
||||
|
||||
def white_rgb(image):
|
||||
rgba = image.convert("RGBA")
|
||||
output = Image.new("RGB", rgba.size, "white")
|
||||
|
||||
output.paste(
|
||||
rgba,
|
||||
mask=rgba.getchannel("A"),
|
||||
)
|
||||
|
||||
rgba.close()
|
||||
return output
|
||||
|
||||
|
||||
def main():
|
||||
# Ограничения дочернего процесса Linux.
|
||||
resource.setrlimit(
|
||||
resource.RLIMIT_AS,
|
||||
(768 * 1024**2,) * 2,
|
||||
)
|
||||
|
||||
resource.setrlimit(
|
||||
resource.RLIMIT_CPU,
|
||||
(20, 21),
|
||||
)
|
||||
|
||||
resource.setrlimit(
|
||||
resource.RLIMIT_FSIZE,
|
||||
(11 * 1024**2,) * 2,
|
||||
)
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
warnings.simplefilter(
|
||||
"error",
|
||||
Image.DecompressionBombWarning,
|
||||
)
|
||||
|
||||
source, output = map(Path, sys.argv[1:3])
|
||||
|
||||
if not 0 < source.stat().st_size <= MAX_BYTES:
|
||||
return 10
|
||||
|
||||
if os.environ.get("IMAGE_TEST_SLEEP") == "1":
|
||||
time.sleep(60)
|
||||
|
||||
try:
|
||||
image = Image.open(source)
|
||||
|
||||
if (
|
||||
image.format not in ("PNG", "JPEG")
|
||||
or image.width * image.height > MAX_PIXELS
|
||||
):
|
||||
image.close()
|
||||
return 10
|
||||
|
||||
image.load()
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
|
||||
except (
|
||||
ValueError,
|
||||
UnidentifiedImageError,
|
||||
OSError,
|
||||
SyntaxError,
|
||||
Image.DecompressionBombWarning,
|
||||
Image.DecompressionBombError,
|
||||
):
|
||||
return 10
|
||||
|
||||
with image:
|
||||
manifest = []
|
||||
|
||||
variants = [
|
||||
("thumbnail", 256, "image/jpeg", "jpg"),
|
||||
("crop", 128, "image/jpeg", "jpg"),
|
||||
("optimized", 1280, "image/webp", "webp"),
|
||||
]
|
||||
|
||||
for name, bound, mime, extension in variants:
|
||||
if name == "crop":
|
||||
scaled = ImageOps.fit(
|
||||
image,
|
||||
(128, 128),
|
||||
method=Image.Resampling.LANCZOS,
|
||||
centering=(0.5, 0.5),
|
||||
)
|
||||
else:
|
||||
scaled = image.resize(
|
||||
fit_size(*image.size, bound),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
|
||||
if extension == "jpg":
|
||||
rendered = white_rgb(scaled)
|
||||
else:
|
||||
rendered = scaled.convert("RGBA")
|
||||
|
||||
scaled.close()
|
||||
|
||||
rendered.info.clear()
|
||||
|
||||
path = output / (name + "." + extension)
|
||||
|
||||
if extension == "jpg":
|
||||
rendered.save(
|
||||
path,
|
||||
"JPEG",
|
||||
quality=85,
|
||||
subsampling=2,
|
||||
optimize=True,
|
||||
exif=b"",
|
||||
icc_profile=None,
|
||||
)
|
||||
else:
|
||||
rendered.save(
|
||||
path,
|
||||
"WEBP",
|
||||
quality=80,
|
||||
method=4,
|
||||
lossless=False,
|
||||
exif=b"",
|
||||
icc_profile=b"",
|
||||
xmp=b"",
|
||||
)
|
||||
|
||||
manifest.append(
|
||||
{
|
||||
"name": name,
|
||||
"content_type": mime,
|
||||
"width": rendered.width,
|
||||
"height": rendered.height,
|
||||
}
|
||||
)
|
||||
|
||||
rendered.close()
|
||||
|
||||
if not 0 < path.stat().st_size <= MAX_BYTES:
|
||||
return 11
|
||||
|
||||
(output / "manifest.json").write_text(
|
||||
json.dumps(manifest),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (MemoryError, OSError):
|
||||
sys.exit(11)
|
||||
@@ -0,0 +1,184 @@
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).with_name("process_image.py")
|
||||
|
||||
|
||||
def execute(folder, expected):
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(SCRIPT),
|
||||
str(folder / "input.bin"),
|
||||
str(folder),
|
||||
],
|
||||
capture_output=True,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
assert result.returncode == expected, (
|
||||
folder.name,
|
||||
result.returncode,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
|
||||
cases = [
|
||||
(
|
||||
"alpha",
|
||||
(320, 200),
|
||||
"RGBA",
|
||||
(255, 0, 0, 0),
|
||||
None,
|
||||
[(256, 160), (128, 128), (320, 200)],
|
||||
),
|
||||
(
|
||||
"small",
|
||||
(20, 10),
|
||||
"RGB",
|
||||
"red",
|
||||
None,
|
||||
[(20, 10), (128, 128), (20, 10)],
|
||||
),
|
||||
(
|
||||
"orientation",
|
||||
(320, 200),
|
||||
"RGB",
|
||||
"blue",
|
||||
6,
|
||||
[(160, 256), (128, 128), (200, 320)],
|
||||
),
|
||||
]
|
||||
|
||||
for label, size, mode, color, orientation, expected in cases:
|
||||
folder = root / label
|
||||
folder.mkdir()
|
||||
|
||||
with Image.new(mode, size, color) as image:
|
||||
if orientation:
|
||||
exif = Image.Exif()
|
||||
exif[274] = orientation
|
||||
|
||||
image.save(
|
||||
folder / "input.bin",
|
||||
"JPEG",
|
||||
exif=exif,
|
||||
)
|
||||
else:
|
||||
image.save(folder / "input.bin", "PNG")
|
||||
|
||||
execute(folder, 0)
|
||||
|
||||
names = [
|
||||
"thumbnail.jpg",
|
||||
"crop.jpg",
|
||||
"optimized.webp",
|
||||
]
|
||||
|
||||
for name, dimensions in zip(names, expected):
|
||||
with Image.open(folder / name) as result:
|
||||
assert result.size == dimensions
|
||||
assert not result.getexif()
|
||||
|
||||
assert not any(
|
||||
result.info.get(key)
|
||||
for key in ["icc_profile", "xmp", "exif"]
|
||||
)
|
||||
|
||||
if label == "alpha" and name.endswith(".jpg"):
|
||||
assert result.getpixel((0, 0)) == (
|
||||
255,
|
||||
255,
|
||||
255,
|
||||
)
|
||||
|
||||
print("PASS:", label)
|
||||
|
||||
folder = root / "center_crop"
|
||||
folder.mkdir()
|
||||
|
||||
with Image.new("RGB", (400, 200), "blue") as image:
|
||||
image.paste("red", (0, 0, 100, 200))
|
||||
image.paste("green", (300, 0, 400, 200))
|
||||
image.save(folder / "input.bin", "PNG")
|
||||
|
||||
execute(folder, 0)
|
||||
|
||||
with Image.open(folder / "crop.jpg") as crop:
|
||||
for x in [32, 96]:
|
||||
red, green, blue = crop.getpixel((x, 64))
|
||||
|
||||
assert blue > 240
|
||||
assert red < 15
|
||||
assert green < 15
|
||||
|
||||
print("PASS: centered crop")
|
||||
|
||||
for label, data in [
|
||||
("broken", b"not an image"),
|
||||
("bytes_limit", b"x" * (10485760 + 1)),
|
||||
]:
|
||||
folder = root / label
|
||||
folder.mkdir()
|
||||
|
||||
(folder / "input.bin").write_bytes(data)
|
||||
|
||||
execute(folder, 10)
|
||||
|
||||
print("PASS rejected:", label)
|
||||
|
||||
folder = root / "pixels"
|
||||
folder.mkdir()
|
||||
|
||||
def chunk(kind, data):
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ kind
|
||||
+ data
|
||||
+ struct.pack(
|
||||
">I",
|
||||
zlib.crc32(kind + data) & 0xffffffff,
|
||||
)
|
||||
)
|
||||
|
||||
png = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(
|
||||
b"IHDR",
|
||||
struct.pack(
|
||||
">IIBBBBB",
|
||||
10000,
|
||||
10000,
|
||||
8,
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
)
|
||||
+ chunk(
|
||||
b"IDAT",
|
||||
zlib.compress(b"\0\0\0\0"),
|
||||
)
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
(folder / "input.bin").write_bytes(png)
|
||||
|
||||
execute(folder, 10)
|
||||
|
||||
print("PASS rejected: pixels before decode")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
FROM golang:1.24.2-bookworm AS builder
|
||||
|
||||
ENV CGO_ENABLED=0
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
RUN git clone --depth 1 \
|
||||
--branch RELEASE.2025-04-22T22-12-26Z \
|
||||
https://github.com/minio/minio.git /src/minio
|
||||
|
||||
WORKDIR /src/minio
|
||||
|
||||
RUN go build -trimpath -o /out/minio .
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
RUN git clone --depth 1 \
|
||||
--branch RELEASE.2025-04-16T18-13-26Z \
|
||||
https://github.com/minio/mc.git /src/mc
|
||||
|
||||
WORKDIR /src/mc
|
||||
|
||||
RUN go build -trimpath -o /out/mc .
|
||||
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=builder /out/minio /usr/local/bin/minio
|
||||
COPY --from=builder /out/mc /usr/local/bin/mc
|
||||
|
||||
RUN mkdir -p /data
|
||||
|
||||
EXPOSE 9000 9001
|
||||
|
||||
ENTRYPOINT ["minio"]
|
||||
CMD ["server", "/data", "--console-address", ":9001"]
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${MINIO_ROOT_USER:?}"
|
||||
: "${MINIO_ROOT_PASSWORD:?}"
|
||||
: "${S3_BUCKET:?}"
|
||||
: "${S3_ACCESS_KEY:?}"
|
||||
: "${S3_SECRET_KEY:?}"
|
||||
|
||||
if [ "$S3_ACCESS_KEY" = "$MINIO_ROOT_USER" ]; then
|
||||
echo "API must use a separate MinIO user" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$S3_SECRET_KEY" = "$MINIO_ROOT_PASSWORD" ]; then
|
||||
echo "API and administrator passwords must differ" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$S3_BUCKET" in
|
||||
""|*[!a-z0-9.-]*)
|
||||
echo "Invalid bucket name" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
mc alias set storage https://minio:9000 \
|
||||
"$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null
|
||||
|
||||
mc mb --ignore-existing "storage/$S3_BUCKET"
|
||||
mc anonymous set none "storage/$S3_BUCKET"
|
||||
|
||||
for role in api worker; do
|
||||
user="messenger_$role"
|
||||
if [ "$role" = api ]; then
|
||||
password="$S3_SECRET_KEY"
|
||||
write_prefix=staging
|
||||
else
|
||||
password="$WORKER_S3_PASSWORD"
|
||||
write_prefix=originals
|
||||
fi
|
||||
read_actions='"s3:GetObject"'
|
||||
if [ "$role" = api ]; then read_actions='"s3:GetObject","s3:DeleteObject"'; fi
|
||||
extra=""
|
||||
if [ "$role" = worker ]; then
|
||||
extra=',"arn:aws:s3:::'"$S3_BUCKET"'/variants/*"'
|
||||
fi
|
||||
cat > /tmp/policy.json <<EOF
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:GetBucketLocation","s3:ListBucket"],"Resource":["arn:aws:s3:::$S3_BUCKET"]},
|
||||
{"Effect":"Allow","Action":[$read_actions],"Resource":["arn:aws:s3:::$S3_BUCKET/originals/*","arn:aws:s3:::$S3_BUCKET/variants/*","arn:aws:s3:::$S3_BUCKET/staging/*"]},
|
||||
{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::$S3_BUCKET/$write_prefix/*"$extra]}]}
|
||||
EOF
|
||||
policy="messenger-$role"
|
||||
mc admin policy create storage "$policy" /tmp/policy.json >/dev/null
|
||||
mc admin user add storage "$user" "$password" >/dev/null
|
||||
if ! mc admin user info --json storage "$user" | grep -Eq '"policyName"[[:space:]]*:[[:space:]]*"'"$policy"'"'; then
|
||||
mc admin policy attach storage "$policy" --user "$user" >/dev/null
|
||||
fi
|
||||
done
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${S3_BUCKET:?}"
|
||||
: "${S3_ACCESS_KEY:?}"
|
||||
: "${S3_SECRET_KEY:?}"
|
||||
|
||||
mc alias set app http://minio:9000 \
|
||||
"$S3_ACCESS_KEY" "$S3_SECRET_KEY" >/dev/null
|
||||
|
||||
TEST_ID="$(cat /proc/sys/kernel/random/uuid)"
|
||||
OBJECT_KEY="originals/access-check-$TEST_ID.txt"
|
||||
OUTSIDE_KEY="outside-access-check-$TEST_ID.txt"
|
||||
|
||||
cleanup() {
|
||||
mc rm --force \
|
||||
"app/$S3_BUCKET/$OBJECT_KEY" >/dev/null 2>&1 || true
|
||||
|
||||
mc rm --force \
|
||||
"app/$S3_BUCKET/$OUTSIDE_KEY" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
|
||||
printf 'private attachment test' > /tmp/expected.txt
|
||||
|
||||
mc cp /tmp/expected.txt \
|
||||
"app/$S3_BUCKET/$OBJECT_KEY" >/dev/null
|
||||
|
||||
mc cat "app/$S3_BUCKET/$OBJECT_KEY" > /tmp/actual.txt
|
||||
|
||||
cmp /tmp/expected.txt /tmp/actual.txt
|
||||
|
||||
echo "PASS: API credentials can upload and download originals"
|
||||
|
||||
HTTP_CODE="$(
|
||||
curl --silent --show-error \
|
||||
--connect-timeout 3 \
|
||||
--max-time 10 \
|
||||
--output /tmp/anonymous-response.xml \
|
||||
--write-out '%{http_code}' \
|
||||
"http://minio:9000/$S3_BUCKET/$OBJECT_KEY"
|
||||
)"
|
||||
|
||||
if [ "$HTTP_CODE" != "403" ]; then
|
||||
echo "FAIL: anonymous GET returned HTTP $HTTP_CODE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -q '<Code>AccessDenied</Code>' \
|
||||
/tmp/anonymous-response.xml
|
||||
then
|
||||
echo "FAIL: expected S3 AccessDenied response" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: anonymous download of an existing object is denied"
|
||||
|
||||
if mc cp /tmp/expected.txt \
|
||||
"app/$S3_BUCKET/$OUTSIDE_KEY" \
|
||||
> /tmp/outside-result.txt 2>&1
|
||||
then
|
||||
echo "FAIL: API credentials can write outside originals/" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -Eiq \
|
||||
'AccessDenied|Access Denied|Insufficient permissions|not authorized|not allowed' \
|
||||
/tmp/outside-result.txt
|
||||
then
|
||||
echo "FAIL: write failed for a reason other than access denial" >&2
|
||||
cat /tmp/outside-result.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: writing outside originals/ is denied"
|
||||
|
||||
if mc admin info app > /tmp/admin-result.txt 2>&1
|
||||
then
|
||||
echo "FAIL: API credentials have administrative access" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -Eiq \
|
||||
'AccessDenied|Access Denied|Insufficient permissions|not authorized|not allowed' \
|
||||
/tmp/admin-result.txt
|
||||
then
|
||||
echo "FAIL: admin command failed for an unexpected reason" >&2
|
||||
cat /tmp/admin-result.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: administrative access is denied"
|
||||
|
||||
mc rm "app/$S3_BUCKET/$OBJECT_KEY" >/dev/null
|
||||
|
||||
echo "PASS: API credentials can delete originals for cleanup"
|
||||
echo "PASS: S3 access checks completed"
|
||||
@@ -0,0 +1,53 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 48
|
||||
batch:
|
||||
timeout: 2s
|
||||
send_batch_size: 256
|
||||
send_batch_max_size: 512
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
otlp/tempo:
|
||||
endpoint: transport:4317
|
||||
tls:
|
||||
insecure: true
|
||||
sending_queue:
|
||||
queue_size: 256
|
||||
retry_on_failure:
|
||||
max_elapsed_time: 60s
|
||||
otlphttp/loki:
|
||||
endpoint: http://transport:3100/otlp
|
||||
sending_queue:
|
||||
queue_size: 256
|
||||
retry_on_failure:
|
||||
max_elapsed_time: 60s
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
service:
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,326 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Messenger — Lab 6",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"editable": true,
|
||||
"refresh": "5s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"tags": [
|
||||
"lab6",
|
||||
"otel"
|
||||
],
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"name": "trace_id",
|
||||
"label": "X-Trace-Id",
|
||||
"type": "textbox",
|
||||
"current": {
|
||||
"text": "",
|
||||
"value": ""
|
||||
},
|
||||
"options": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "API — RPS (без health)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(messenger_http_requests_total{service_name=\"messenger-api\"}[1m]))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "API — 5xx / все запросы",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",status_class=\"5xx\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name=\"messenger-api\"}[1m])), 0.000001)",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "API — p95 по всем репликам",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "API — RPS по route / status",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (route,status_class) (rate(messenger_http_requests_total{service_name=\"messenger-api\"}[1m]))",
|
||||
"legendFormat": "{{route}} {{status_class}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Worker — успешные / ошибочные / пропущенные доставки",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (increase(messenger_jobs_total{service_name=\"messenger-worker\"}[5m]))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Worker — p95 processing duration",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le,outcome) (rate(messenger_job_duration_seconds_bucket{service_name=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "API — структурные логи",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-api\"}",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": ""
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"showTime": true,
|
||||
"showLabels": false,
|
||||
"wrapLogMessage": true,
|
||||
"sortOrder": "Descending"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Worker — структурные логи",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-worker\"}",
|
||||
"legendFormat": ""
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": ""
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"showTime": true,
|
||||
"showLabels": false,
|
||||
"wrapLogMessage": true,
|
||||
"sortOrder": "Descending"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Трасса по X-Trace-Id",
|
||||
"type": "traces",
|
||||
"datasource": {
|
||||
"type": "tempo",
|
||||
"uid": "tempo"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 24,
|
||||
"h": 10
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"queryType": "traceId",
|
||||
"query": "${trace_id}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: Messenger
|
||||
folder: Lab 6
|
||||
type: file
|
||||
disableDeletion: true
|
||||
updateIntervalSeconds: 10
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,37 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://transport:9090
|
||||
isDefault: true
|
||||
jsonData:
|
||||
timeInterval: 5s
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://transport:3100
|
||||
jsonData:
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
urlDisplayLabel: Open trace
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://transport:3200
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-1m'
|
||||
spanEndTimeShift: '1m'
|
||||
filterByTraceID: false
|
||||
filterBySpanID: false
|
||||
customQuery: true
|
||||
query: '{service_name=~"messenger-api|messenger-worker"} | trace_id="$${__trace.traceId}"'
|
||||
@@ -0,0 +1,32 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
common:
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
instance_addr: 127.0.0.1
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 168h
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,6 @@
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
scrape_configs:
|
||||
- job_name: messenger-otel
|
||||
static_configs:
|
||||
- targets: ['transport:8889']
|
||||
@@ -0,0 +1,24 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
ingester:
|
||||
max_block_duration: 5m
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,34 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in8443
|
||||
bind :8443 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str lb }
|
||||
default_backend local8443
|
||||
backend local8443
|
||||
server local 127.0.0.1:8080 resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out5672
|
||||
bind 127.0.0.1:5672
|
||||
server secure rabbitmq-tls:5672 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost rabbitmq-tls sni str(rabbitmq-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out9000
|
||||
bind 127.0.0.1:9000
|
||||
server secure minio-tls:9000 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost minio-tls sni str(minio-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out4318
|
||||
bind 127.0.0.1:4318
|
||||
server secure otel-collector-tls:4318 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost otel-collector-tls sni str(otel-collector-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out6379
|
||||
bind 127.0.0.1:6379
|
||||
server secure redis-tls:6379 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost redis-tls sni str(redis-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,27 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
listen out9090
|
||||
bind 172.29.127.2:9090
|
||||
server secure prometheus-tls:9090 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost prometheus-tls sni str(prometheus-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out3100
|
||||
bind 172.29.127.2:3100
|
||||
server secure loki-tls:3100 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost loki-tls sni str(loki-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out3200
|
||||
bind 172.29.127.2:3200
|
||||
server secure tempo-tls:3200 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost tempo-tls sni str(tempo-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen admin
|
||||
bind :3443 ssl crt /identity/bundle.pem
|
||||
server local grafana:3000 resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,22 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in3100
|
||||
mode http
|
||||
bind :3100 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str otel-collector grafana }
|
||||
http-request deny if { ssl_c_s_dn(cn) -m str grafana } !{ method GET HEAD }
|
||||
http-request deny if { ssl_c_s_dn(cn) -m str otel-collector } !{ path /otlp/v1/logs }
|
||||
default_backend local3100
|
||||
backend local3100
|
||||
mode http
|
||||
server local loki:3100 resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,33 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in4318
|
||||
bind :4318 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str api worker }
|
||||
default_backend local4318
|
||||
backend local4318
|
||||
server local otel-collector:4318 resolvers docker init-addr last,libc,none
|
||||
|
||||
frontend in8889
|
||||
bind :8889 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str prometheus }
|
||||
default_backend local8889
|
||||
backend local8889
|
||||
server local otel-collector:8889 resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out4317
|
||||
bind 172.29.123.2:4317
|
||||
server secure tempo-tls:4317 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost tempo-tls sni str(tempo-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out3100
|
||||
bind 172.29.123.2:3100
|
||||
server secure loki-tls:3100 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost loki-tls sni str(loki-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,22 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in9090
|
||||
bind :9090 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str grafana }
|
||||
default_backend local9090
|
||||
backend local9090
|
||||
server local prometheus:9090 resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out8889
|
||||
bind 172.29.124.2:8889
|
||||
server secure otel-collector-tls:8889 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost otel-collector-tls sni str(otel-collector-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,25 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in4317
|
||||
bind :4317 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str otel-collector }
|
||||
default_backend local4317
|
||||
backend local4317
|
||||
server local tempo:4317 resolvers docker init-addr last,libc,none
|
||||
|
||||
frontend in3200
|
||||
bind :3200 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str grafana }
|
||||
default_backend local3200
|
||||
backend local3200
|
||||
server local tempo:3200 resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,23 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
listen out5672
|
||||
bind 127.0.0.1:5672
|
||||
server secure rabbitmq-tls:5672 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost rabbitmq-tls sni str(rabbitmq-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out9000
|
||||
bind 127.0.0.1:9000
|
||||
server secure minio-tls:9000 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost minio-tls sni str(minio-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out4318
|
||||
bind 127.0.0.1:4318
|
||||
server secure otel-collector-tls:4318 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost otel-collector-tls sni str(otel-collector-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,2 @@
|
||||
local all all trust
|
||||
hostssl all all all scram-sha-256
|
||||
@@ -0,0 +1,10 @@
|
||||
definitions.import_backend = local_filesystem
|
||||
definitions.local.path = /etc/rabbitmq/definitions.json
|
||||
listeners.tcp = none
|
||||
listeners.ssl.default = 5672
|
||||
ssl_options.cacertfile = /identity/ca.crt
|
||||
ssl_options.certfile = /identity/cert.pem
|
||||
ssl_options.keyfile = /identity/key.pem
|
||||
ssl_options.verify = verify_peer
|
||||
ssl_options.fail_if_no_peer_cert = true
|
||||
distribution.listener.interface = 127.0.0.1
|
||||
@@ -0,0 +1,34 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in8443
|
||||
bind :8443 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str lb }
|
||||
default_backend local8443
|
||||
backend local8443
|
||||
server local 127.0.0.1:8080 resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out5672
|
||||
bind 127.0.0.1:5672
|
||||
server secure rabbitmq-tls:5672 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost rabbitmq-tls sni str(rabbitmq-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out9000
|
||||
bind 127.0.0.1:9000
|
||||
server secure minio-tls:9000 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost minio-tls sni str(minio-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out4318
|
||||
bind 127.0.0.1:4318
|
||||
server secure otel-collector-tls:4318 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost otel-collector-tls sni str(otel-collector-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out6379
|
||||
bind 127.0.0.1:6379
|
||||
server secure redis-tls:6379 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost redis-tls sni str(redis-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,27 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
listen out9090
|
||||
bind 172.29.127.2:9090
|
||||
server secure prometheus-tls:9090 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost prometheus-tls sni str(prometheus-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out3100
|
||||
bind 172.29.127.2:3100
|
||||
server secure loki-tls:3100 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost loki-tls sni str(loki-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out3200
|
||||
bind 172.29.127.2:3200
|
||||
server secure tempo-tls:3200 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost tempo-tls sni str(tempo-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen admin
|
||||
bind :3443 ssl crt /identity/bundle.pem
|
||||
server local grafana:3000 resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,22 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in3100
|
||||
mode http
|
||||
bind :3100 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str otel-collector grafana }
|
||||
http-request deny if { ssl_c_s_dn(cn) -m str grafana } !{ method GET HEAD }
|
||||
http-request deny if { ssl_c_s_dn(cn) -m str otel-collector } !{ path /otlp/v1/logs }
|
||||
default_backend local3100
|
||||
backend local3100
|
||||
mode http
|
||||
server local loki:3100 resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,33 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in4318
|
||||
bind :4318 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str api worker }
|
||||
default_backend local4318
|
||||
backend local4318
|
||||
server local otel-collector:4318 resolvers docker init-addr last,libc,none
|
||||
|
||||
frontend in8889
|
||||
bind :8889 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str prometheus }
|
||||
default_backend local8889
|
||||
backend local8889
|
||||
server local otel-collector:8889 resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out4317
|
||||
bind 172.29.123.2:4317
|
||||
server secure tempo-tls:4317 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost tempo-tls sni str(tempo-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out3100
|
||||
bind 172.29.123.2:3100
|
||||
server secure loki-tls:3100 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost loki-tls sni str(loki-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,22 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in9090
|
||||
bind :9090 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str grafana }
|
||||
default_backend local9090
|
||||
backend local9090
|
||||
server local prometheus:9090 resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out8889
|
||||
bind 172.29.124.2:8889
|
||||
server secure otel-collector-tls:8889 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost otel-collector-tls sni str(otel-collector-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,25 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
frontend in4317
|
||||
bind :4317 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str otel-collector }
|
||||
default_backend local4317
|
||||
backend local4317
|
||||
server local tempo:4317 resolvers docker init-addr last,libc,none
|
||||
|
||||
frontend in3200
|
||||
bind :3200 ssl crt /identity/bundle.pem ca-file /identity/ca.crt verify required
|
||||
tcp-request content reject unless { ssl_c_s_dn(cn) -m str grafana }
|
||||
default_backend local3200
|
||||
backend local3200
|
||||
server local tempo:3200 resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,23 @@
|
||||
global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 2s
|
||||
|
||||
listen out5672
|
||||
bind 127.0.0.1:5672
|
||||
server secure rabbitmq-tls:5672 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost rabbitmq-tls sni str(rabbitmq-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out9000
|
||||
bind 127.0.0.1:9000
|
||||
server secure minio-tls:9000 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost minio-tls sni str(minio-tls) resolvers docker init-addr last,libc,none
|
||||
|
||||
listen out4318
|
||||
bind 127.0.0.1:4318
|
||||
server secure otel-collector-tls:4318 ssl verify required ca-file /identity/ca.crt crt /identity/bundle.pem verifyhost otel-collector-tls sni str(otel-collector-tls) resolvers docker init-addr last,libc,none
|
||||
@@ -0,0 +1,33 @@
|
||||
HELP.md
|
||||
target/
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
|
||||
@@ -0,0 +1,295 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
if [ -n "${JAVA_HOME-}" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
Vendored
+189
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.3.5</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.vnp</groupId>
|
||||
<artifactId>demo</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>mtusi-messenger</name>
|
||||
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
<maven.compiler.release>21</maven.compiler.release>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-bom</artifactId>
|
||||
<version>1.44.1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-sdk</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-exporter-otlp</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-sdk-testing</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Web -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Validation -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Actuator -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Data JPA -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- PostgreSQL -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- Redis -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Flyway -->
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Security -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Boot Tests -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.78.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- REST Assured -->
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.minio</groupId>
|
||||
<artifactId>minio</artifactId>
|
||||
<version>8.5.17</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.drewnoakes</groupId>
|
||||
<artifactId>metadata-extractor</artifactId>
|
||||
<version>2.19.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
<!-- Spring Boot Maven Plugin -->
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.vnp.demo.MessengerApplication</mainClass>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.vnp.demo;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private final String code;
|
||||
private final HttpStatus status;
|
||||
|
||||
public BusinessException(String code, String message, HttpStatus status) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public HttpStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public static BusinessException notFound() {
|
||||
return new BusinessException(
|
||||
"not_found",
|
||||
"Объект не найден",
|
||||
HttpStatus.NOT_FOUND
|
||||
);
|
||||
}
|
||||
|
||||
public static BusinessException conflict() {
|
||||
return conflict("Конфликт");
|
||||
}
|
||||
|
||||
public static BusinessException conflict(String message) {
|
||||
return new BusinessException(
|
||||
"conflict",
|
||||
message,
|
||||
HttpStatus.CONFLICT
|
||||
);
|
||||
}
|
||||
|
||||
public static BusinessException unauthorized() {
|
||||
return unauthorized("Пользователь не найден");
|
||||
}
|
||||
|
||||
public static BusinessException unauthorized(String message) {
|
||||
return new BusinessException(
|
||||
"unauthorized",
|
||||
message,
|
||||
HttpStatus.UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
|
||||
public static BusinessException invalid(String message) {
|
||||
return new BusinessException(
|
||||
"invalid_request",
|
||||
message,
|
||||
HttpStatus.BAD_REQUEST
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.vnp.demo;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CursorCodec {
|
||||
|
||||
public record ChatCursor(Instant createdAt, UUID id) {
|
||||
}
|
||||
|
||||
public record MessageCursor(Instant createdAt, UUID id) {
|
||||
}
|
||||
|
||||
public String encodeIndex(int index) {
|
||||
return Base64.getUrlEncoder()
|
||||
.withoutPadding()
|
||||
.encodeToString(
|
||||
("i:" + index).getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
}
|
||||
|
||||
public int decodeIndex(String cursor, int size) {
|
||||
try {
|
||||
String decoded = new String(
|
||||
Base64.getUrlDecoder().decode(cursor),
|
||||
StandardCharsets.UTF_8
|
||||
);
|
||||
|
||||
if (!decoded.startsWith("i:")) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
int idx = Integer.parseInt(decoded.substring(2));
|
||||
|
||||
if (idx < 0 || idx > size) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
return idx;
|
||||
|
||||
} catch (IllegalArgumentException ex) {
|
||||
throw BusinessException.invalid("Неверный cursor");
|
||||
}
|
||||
}
|
||||
|
||||
public String encodeChat(
|
||||
UUID userId,
|
||||
Instant createdAt,
|
||||
UUID chatId
|
||||
) {
|
||||
String value = "chat:v1:"
|
||||
+ userId + ":"
|
||||
+ createdAt + ":"
|
||||
+ chatId;
|
||||
|
||||
return Base64.getUrlEncoder()
|
||||
.withoutPadding()
|
||||
.encodeToString(
|
||||
value.getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
}
|
||||
|
||||
public ChatCursor decodeChat(String cursor, UUID userId) {
|
||||
try {
|
||||
String value = decodeBase64(cursor);
|
||||
|
||||
if (!value.startsWith("chat:v1:")) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
String content = value.substring("chat:v1:".length());
|
||||
|
||||
int firstSeparator = content.indexOf(':');
|
||||
int lastSeparator = content.lastIndexOf(':');
|
||||
|
||||
if (firstSeparator < 0
|
||||
|| lastSeparator <= firstSeparator) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
UUID cursorUserId = UUID.fromString(
|
||||
content.substring(0, firstSeparator)
|
||||
);
|
||||
|
||||
if (!cursorUserId.equals(userId)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
Instant createdAt = Instant.parse(
|
||||
content.substring(
|
||||
firstSeparator + 1,
|
||||
lastSeparator
|
||||
)
|
||||
);
|
||||
|
||||
UUID chatId = UUID.fromString(
|
||||
content.substring(lastSeparator + 1)
|
||||
);
|
||||
|
||||
return new ChatCursor(createdAt, chatId);
|
||||
|
||||
} catch (IllegalArgumentException | DateTimeParseException ex) {
|
||||
throw BusinessException.invalid("Неверный cursor");
|
||||
}
|
||||
}
|
||||
|
||||
public String encodeMessage(
|
||||
UUID chatId,
|
||||
Instant createdAt,
|
||||
UUID messageId
|
||||
) {
|
||||
String value = "message:v1:"
|
||||
+ chatId + ":"
|
||||
+ createdAt + ":"
|
||||
+ messageId;
|
||||
|
||||
return Base64.getUrlEncoder()
|
||||
.withoutPadding()
|
||||
.encodeToString(
|
||||
value.getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
}
|
||||
|
||||
public MessageCursor decodeMessage(String cursor, UUID chatId) {
|
||||
try {
|
||||
String value = decodeBase64(cursor);
|
||||
|
||||
if (!value.startsWith("message:v1:")) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
String content = value.substring("message:v1:".length());
|
||||
|
||||
int firstSeparator = content.indexOf(':');
|
||||
int lastSeparator = content.lastIndexOf(':');
|
||||
|
||||
if (firstSeparator < 0
|
||||
|| lastSeparator <= firstSeparator) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
UUID cursorChatId = UUID.fromString(
|
||||
content.substring(0, firstSeparator)
|
||||
);
|
||||
|
||||
if (!cursorChatId.equals(chatId)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
Instant createdAt = Instant.parse(
|
||||
content.substring(
|
||||
firstSeparator + 1,
|
||||
lastSeparator
|
||||
)
|
||||
);
|
||||
|
||||
UUID messageId = UUID.fromString(
|
||||
content.substring(lastSeparator + 1)
|
||||
);
|
||||
|
||||
return new MessageCursor(createdAt, messageId);
|
||||
|
||||
} catch (IllegalArgumentException | DateTimeParseException ex) {
|
||||
throw BusinessException.invalid("Неверный cursor");
|
||||
}
|
||||
}
|
||||
|
||||
private String decodeBase64(String cursor) {
|
||||
if (cursor == null || cursor.isBlank()) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
return new String(
|
||||
Base64.getUrlDecoder().decode(cursor),
|
||||
StandardCharsets.UTF_8
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
|
||||
package com.vnp.demo;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingRequestHeaderException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
import com.vnp.demo.dto.ErrorResponse;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private ErrorResponse build(String code, String msg) {
|
||||
return new ErrorResponse(
|
||||
new ErrorResponse.ErrorBody(
|
||||
code,
|
||||
msg,
|
||||
MDC.get("requestId")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBusiness(
|
||||
BusinessException e,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
ResponseEntity.BodyBuilder builder =
|
||||
ResponseEntity.status(e.getStatus());
|
||||
|
||||
if (e.getStatus() == HttpStatus.TOO_MANY_REQUESTS) {
|
||||
builder.header("Retry-After", "1");
|
||||
}
|
||||
|
||||
if (e.getStatus() == HttpStatus.UNAUTHORIZED) {
|
||||
String path = request.getRequestURI();
|
||||
|
||||
String challenge = path.equals("/api/v1/auth/sessions")
|
||||
? "Basic realm=\"messenger\", charset=\"UTF-8\""
|
||||
: "Bearer realm=\"messenger\"";
|
||||
|
||||
builder.header("WWW-Authenticate", challenge);
|
||||
}
|
||||
|
||||
return builder.body(
|
||||
build(e.getCode(), e.getMessage())
|
||||
);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorResponse> handleValidation(
|
||||
MethodArgumentNotValidException e
|
||||
) {
|
||||
String msg = e.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.findFirst()
|
||||
.map(f -> f.getField() + ": " + f.getDefaultMessage())
|
||||
.orElse("Ошибка валидации");
|
||||
|
||||
return ResponseEntity.badRequest()
|
||||
.body(build("invalid_request", msg));
|
||||
}
|
||||
|
||||
@ExceptionHandler({
|
||||
HttpMessageNotReadableException.class,
|
||||
MethodArgumentTypeMismatchException.class
|
||||
})
|
||||
public ResponseEntity<ErrorResponse> handleMalformed(Exception e) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(build(
|
||||
"invalid_request",
|
||||
"Неверный формат запроса"
|
||||
));
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleNotFound(
|
||||
NoResourceFoundException e
|
||||
) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(build(
|
||||
"not_found",
|
||||
"Ресурс не найден"
|
||||
));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMissingHeader(
|
||||
MissingRequestHeaderException e
|
||||
) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(build(
|
||||
"invalid_request",
|
||||
"Отсутствует обязательный заголовок: "
|
||||
+ e.getHeaderName()
|
||||
));
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataAccessException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataAccess(
|
||||
DataAccessException e
|
||||
) {
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(build(
|
||||
"unavailable",
|
||||
"Сервис временно недоступен"
|
||||
));
|
||||
}
|
||||
|
||||
@ExceptionHandler(ResponseStatusException.class)
|
||||
public ResponseEntity<ErrorResponse> handleStatus(
|
||||
ResponseStatusException e
|
||||
) {
|
||||
int status = e.getStatusCode().value();
|
||||
|
||||
String code = status == 503
|
||||
? "unavailable"
|
||||
: "request_failed";
|
||||
|
||||
String message = status == 503
|
||||
? "Сервис временно недоступен"
|
||||
: "Запрос не может быть выполнен";
|
||||
|
||||
return ResponseEntity.status(status)
|
||||
.body(build(code, message));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleGeneric(Exception e) {
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(build(
|
||||
"internal_error",
|
||||
"Внутренняя ошибка"
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.vnp.demo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MessengerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MessengerApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.vnp.demo;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class SessionStoreExceptionHandler {
|
||||
|
||||
@ExceptionHandler(SessionStoreUnavailableException.class)
|
||||
public ResponseEntity<Map<String, String>> handleSessionStoreUnavailable(
|
||||
SessionStoreUnavailableException ex
|
||||
) {
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(Map.of(
|
||||
"error", "SERVICE_UNAVAILABLE",
|
||||
"message", "Session storage is temporarily unavailable"
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.vnp.demo;
|
||||
|
||||
public class SessionStoreUnavailableException extends RuntimeException {
|
||||
|
||||
public SessionStoreUnavailableException(Throwable cause) {
|
||||
super("Session storage is temporarily unavailable", cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package main.java.com.vnp.demo.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.fasterxml.jackson.databind.cfg.CoercionAction;
|
||||
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
|
||||
import com.fasterxml.jackson.databind.type.LogicalType;
|
||||
|
||||
@Configuration
|
||||
public class JacksonConfig {
|
||||
@Bean
|
||||
public Jackson2ObjectMapperBuilderCustomizer strictTextValues() {
|
||||
return builder -> builder.postConfigurer(mapper ->
|
||||
mapper.coercionConfigFor(LogicalType.Textual)
|
||||
.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail)
|
||||
.setCoercion(CoercionInputShape.Float, CoercionAction.Fail)
|
||||
.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.vnp.demo.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
public class PasswordBenchmark {
|
||||
public static void main(String[] args) {
|
||||
PasswordEncoder encoder = new PasswordConfig().passwordEncoder();
|
||||
String sample = "local-benchmark-input";
|
||||
String hash = encoder.encode(sample);
|
||||
if (!hash.startsWith("$argon2id$v=19$m=19456,t=2,p=1$") ||
|
||||
hash.equals(encoder.encode(sample))) {
|
||||
throw new IllegalStateException("Unexpected parameters or repeated salt");
|
||||
}
|
||||
long[] millis = new long[25];
|
||||
for (int i = -5; i < millis.length; i++) {
|
||||
long start = System.nanoTime();
|
||||
if (!encoder.matches(sample, hash)) throw new IllegalStateException("Verification failed");
|
||||
if (i >= 0) millis[i] = (System.nanoTime() - start) / 1_000_000;
|
||||
}
|
||||
Arrays.sort(millis);
|
||||
System.out.printf("Argon2id m=19456 KiB t=2 p=1 n=25 verify p50=%d ms p95=%d ms%n", millis[12], millis[23]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.vnp.demo.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class PasswordConfig {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new Argon2PasswordEncoder(16, 32, 1, 19456, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.vnp.demo.config;
|
||||
|
||||
import org.springframework.amqp.core.Declarables;
|
||||
import org.springframework.amqp.core.Queue;
|
||||
import org.springframework.amqp.core.QueueBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class RabbitConfig {
|
||||
|
||||
public static final String QUEUE = "attachments.v1";
|
||||
public static final String DLQ = "attachments.v1.dlq";
|
||||
|
||||
@Bean
|
||||
public Declarables attachmentQueues() {
|
||||
return new Declarables(
|
||||
new Queue(DLQ, true),
|
||||
|
||||
QueueBuilder.durable(QUEUE)
|
||||
.deadLetterExchange("")
|
||||
.deadLetterRoutingKey(DLQ)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.vnp.demo.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
public class SchedulingConfig {
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.vnp.demo.config;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.vnp.demo.filter.BearerAuthenticationFilter;
|
||||
import com.vnp.demo.service.AuthService;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(
|
||||
HttpSecurity http,
|
||||
AuthService authService,
|
||||
ObjectMapper objectMapper
|
||||
) throws Exception {
|
||||
|
||||
return http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.httpBasic(basic -> basic.disable())
|
||||
.formLogin(form -> form.disable())
|
||||
.sessionManagement(session -> session
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(
|
||||
"/health/live",
|
||||
"/health/ready"
|
||||
).permitAll()
|
||||
.requestMatchers(
|
||||
org.springframework.http.HttpMethod.POST,
|
||||
"/api/v1/users",
|
||||
"/api/v1/auth/sessions"
|
||||
).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.exceptionHandling(ex -> ex
|
||||
.authenticationEntryPoint((request, response, exception) -> {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setHeader(
|
||||
HttpHeaders.WWW_AUTHENTICATE,
|
||||
"Bearer realm=\"messenger\""
|
||||
);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
|
||||
objectMapper.writeValue(
|
||||
response.getWriter(),
|
||||
Map.of("error", Map.of(
|
||||
"code", "unauthorized",
|
||||
"message", "Требуется авторизация",
|
||||
"request_id", response.getHeader("X-Request-Id")
|
||||
))
|
||||
);
|
||||
})
|
||||
)
|
||||
.addFilterBefore(
|
||||
new BearerAuthenticationFilter(authService, objectMapper),
|
||||
UsernamePasswordAuthenticationFilter.class
|
||||
)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.vnp.demo.config;
|
||||
|
||||
import org.apache.coyote.http11.AbstractHttp11Protocol;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class UploadTimeoutConfig {
|
||||
|
||||
@Bean
|
||||
public WebServerFactoryCustomizer<TomcatServletWebServerFactory>
|
||||
uploadTimeoutCustomizer() {
|
||||
|
||||
return factory -> factory.addConnectorCustomizers(connector -> {
|
||||
if (connector.getProtocolHandler()
|
||||
instanceof AbstractHttp11Protocol<?> protocol) {
|
||||
|
||||
protocol.setDisableUploadTimeout(false);
|
||||
protocol.setConnectionUploadTimeout(15_000);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.vnp.demo.controllers;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.vnp.demo.BusinessException;
|
||||
import com.vnp.demo.dto.AttachmentResponse;
|
||||
import com.vnp.demo.service.AttachmentService;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1")
|
||||
public class AttachmentController {
|
||||
|
||||
private final AttachmentService attachmentService;
|
||||
|
||||
public AttachmentController(
|
||||
AttachmentService attachmentService
|
||||
) {
|
||||
this.attachmentService = attachmentService;
|
||||
}
|
||||
|
||||
@PostMapping("/chats/{chat_id}/attachments")
|
||||
@ResponseStatus(HttpStatus.ACCEPTED)
|
||||
public AttachmentResponse upload(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@RequestParam(value = "filename", required = false)
|
||||
String filename,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
try {
|
||||
return attachmentService.upload(
|
||||
userId,
|
||||
chatId,
|
||||
filename,
|
||||
request.getContentType(),
|
||||
request.getContentLengthLong(),
|
||||
request.getInputStream()
|
||||
);
|
||||
} catch (IOException e) {
|
||||
throw BusinessException.invalid(
|
||||
"Не удалось прочитать тело запроса"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/attachments/{id}")
|
||||
public AttachmentResponse metadata(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@PathVariable("id") UUID id
|
||||
) {
|
||||
return attachmentService.getMetadata(userId, id);
|
||||
}
|
||||
|
||||
@GetMapping("/attachments/{id}/content")
|
||||
public ResponseEntity<byte[]> content(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@PathVariable("id") UUID id,
|
||||
@RequestParam(defaultValue = "original")
|
||||
String variant
|
||||
) {
|
||||
AttachmentService.Download download =
|
||||
attachmentService.download(userId, id, variant);
|
||||
|
||||
String disposition = ContentDisposition.attachment()
|
||||
.filename(
|
||||
download.filename(),
|
||||
StandardCharsets.UTF_8
|
||||
)
|
||||
.build()
|
||||
.toString();
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(
|
||||
MediaType.parseMediaType(download.contentType())
|
||||
)
|
||||
.contentLength(download.bytes().length)
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, disposition)
|
||||
.header(HttpHeaders.CACHE_CONTROL, "private, no-store")
|
||||
.header("X-Content-Type-Options", "nosniff")
|
||||
.body(download.bytes());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.vnp.demo.controllers;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.vnp.demo.BusinessException;
|
||||
import com.vnp.demo.dto.SessionResponse;
|
||||
import com.vnp.demo.service.AuthService;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth/sessions")
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(AuthService authService) {
|
||||
this.authService = authService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public SessionResponse login(
|
||||
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false)
|
||||
String authorization,
|
||||
HttpServletRequest request
|
||||
) throws IOException {
|
||||
if (request.getInputStream().read() != -1) {
|
||||
throw BusinessException.invalid("Тело запроса создания сессии должно быть пустым");
|
||||
}
|
||||
if (authorization == null
|
||||
|| !authorization.startsWith("Basic ")) {
|
||||
throw BusinessException.unauthorized();
|
||||
}
|
||||
|
||||
String encoded = authorization.substring(6).trim();
|
||||
String credentials;
|
||||
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(encoded);
|
||||
|
||||
credentials = StandardCharsets.UTF_8
|
||||
.newDecoder()
|
||||
.decode(ByteBuffer.wrap(decoded))
|
||||
.toString();
|
||||
|
||||
} catch (IllegalArgumentException | CharacterCodingException ex) {
|
||||
throw BusinessException.unauthorized();
|
||||
}
|
||||
|
||||
int separator = credentials.indexOf(':');
|
||||
|
||||
if (separator < 0) {
|
||||
throw BusinessException.unauthorized();
|
||||
}
|
||||
|
||||
String username = credentials.substring(0, separator);
|
||||
String password = credentials.substring(separator + 1);
|
||||
|
||||
if (!username.matches("[a-z0-9_]{3,32}")) {
|
||||
throw BusinessException.unauthorized();
|
||||
}
|
||||
|
||||
return authService.login(username, password);
|
||||
}
|
||||
|
||||
@DeleteMapping("/current")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void logout(
|
||||
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false)
|
||||
String authorization
|
||||
) {
|
||||
if (authorization == null
|
||||
|| !authorization.startsWith("Bearer ")) {
|
||||
throw BusinessException.unauthorized();
|
||||
}
|
||||
|
||||
authService.logout(authorization.substring(7).trim());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.vnp.demo.controllers;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.vnp.demo.dto.ChatCreateRequest;
|
||||
import com.vnp.demo.dto.ChatPageResponse;
|
||||
import com.vnp.demo.dto.ChatResponse;
|
||||
import com.vnp.demo.service.ChatService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats")
|
||||
public class ChatController {
|
||||
|
||||
private final ChatService chatService;
|
||||
|
||||
public ChatController(ChatService chatService) {
|
||||
this.chatService = chatService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public ChatResponse create(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@Valid @RequestBody ChatCreateRequest request
|
||||
) {
|
||||
return chatService.create(userId, request);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ChatPageResponse list(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@RequestParam(defaultValue = "50") int limit,
|
||||
@RequestParam(required = false) String cursor
|
||||
) {
|
||||
return chatService.list(userId, limit, cursor);
|
||||
}
|
||||
|
||||
@GetMapping("/{chat_id}")
|
||||
public ChatResponse get(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@PathVariable("chat_id") UUID chatId
|
||||
) {
|
||||
return chatService.get(userId, chatId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.vnp.demo.controllers;
|
||||
|
||||
import org.springframework.boot.availability.ApplicationAvailability;
|
||||
import org.springframework.boot.availability.ReadinessState;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.vnp.demo.service.S3StorageService;
|
||||
|
||||
import com.vnp.demo.BusinessException;
|
||||
import com.vnp.demo.dto.HealthResponse;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/health")
|
||||
public class HealthController {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final StringRedisTemplate redis;
|
||||
private final ApplicationAvailability availability;
|
||||
private final S3StorageService storage;
|
||||
public HealthController(
|
||||
JdbcTemplate jdbc,
|
||||
StringRedisTemplate redis,
|
||||
ApplicationAvailability availability,
|
||||
S3StorageService storage
|
||||
) {
|
||||
this.jdbc = jdbc;
|
||||
this.redis = redis;
|
||||
this.availability = availability;
|
||||
this.storage = storage;
|
||||
}
|
||||
@GetMapping("/live")
|
||||
public HealthResponse live() { return HealthResponse.ok(); }
|
||||
@GetMapping("/ready")
|
||||
public HealthResponse ready() {
|
||||
try {
|
||||
if (availability.getReadinessState() != ReadinessState.ACCEPTING_TRAFFIC) throw new IllegalStateException();
|
||||
if (!Integer.valueOf(1).equals(jdbc.queryForObject("SELECT 1", Integer.class))) throw new IllegalStateException();
|
||||
String pong = redis.execute((org.springframework.data.redis.core.RedisCallback<String>) c -> c.ping());
|
||||
if (!"PONG".equals(pong)) throw new IllegalStateException();
|
||||
storage.checkReady();
|
||||
return HealthResponse.ok();
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("service_unavailable", "Сервис не готов", HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.vnp.demo.controllers;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.vnp.demo.dto.MessageCreateRequest;
|
||||
import com.vnp.demo.dto.MessagePageResponse;
|
||||
import com.vnp.demo.dto.MessageResponse;
|
||||
import com.vnp.demo.service.MessageService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats/{chat_id}/messages")
|
||||
public class MessageController {
|
||||
|
||||
private final MessageService messageService;
|
||||
|
||||
public MessageController(MessageService messageService) {
|
||||
this.messageService = messageService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public MessageResponse create(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@org.springframework.web.bind.annotation.RequestHeader("Idempotency-Key") String key,
|
||||
@Valid @RequestBody MessageCreateRequest request
|
||||
) {
|
||||
return messageService.create(userId, chatId, request, key);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public MessagePageResponse list(
|
||||
@AuthenticationPrincipal UUID userId,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@RequestParam(defaultValue = "50") int limit,
|
||||
@RequestParam(required = false) String cursor
|
||||
) {
|
||||
return messageService.list(userId, chatId, limit, cursor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.vnp.demo.controllers;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.vnp.demo.dto.UserCreateRequest;
|
||||
import com.vnp.demo.dto.UserResponse;
|
||||
import com.vnp.demo.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public UserResponse register(
|
||||
@Valid @RequestBody UserCreateRequest request
|
||||
) {
|
||||
return userService.register(request);
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public UserResponse getCurrent(
|
||||
@AuthenticationPrincipal UUID userId
|
||||
) {
|
||||
return userService.getCurrent(userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record AttachmentJobMessage(
|
||||
@JsonProperty("schema_version")
|
||||
int schemaVersion,
|
||||
|
||||
@JsonProperty("job_id")
|
||||
UUID jobId,
|
||||
|
||||
String type,
|
||||
|
||||
@JsonProperty("attachment_id")
|
||||
UUID attachmentId,
|
||||
|
||||
@JsonProperty("pipeline_version")
|
||||
int pipelineVersion,
|
||||
|
||||
int attempt,
|
||||
|
||||
@JsonProperty("created_at")
|
||||
Instant createdAt
|
||||
) {
|
||||
public static final int SCHEMA_VERSION = 1;
|
||||
|
||||
public static final String TYPE =
|
||||
"attachment.process.v1";
|
||||
|
||||
public AttachmentJobMessage {
|
||||
if (schemaVersion != SCHEMA_VERSION) {
|
||||
throw new IllegalArgumentException(
|
||||
"Unsupported job schema version"
|
||||
);
|
||||
}
|
||||
|
||||
if (!TYPE.equals(type)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Unsupported job type"
|
||||
);
|
||||
}
|
||||
|
||||
Objects.requireNonNull(jobId, "jobId");
|
||||
Objects.requireNonNull(attachmentId, "attachmentId");
|
||||
Objects.requireNonNull(createdAt, "createdAt");
|
||||
|
||||
if (pipelineVersion < 1) {
|
||||
throw new IllegalArgumentException(
|
||||
"pipelineVersion must be positive"
|
||||
);
|
||||
}
|
||||
|
||||
if (attempt < 1) {
|
||||
throw new IllegalArgumentException(
|
||||
"attempt must be positive"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static AttachmentJobMessage create(
|
||||
UUID jobId,
|
||||
UUID attachmentId,
|
||||
int pipelineVersion,
|
||||
int attempt,
|
||||
Instant createdAt
|
||||
) {
|
||||
return new AttachmentJobMessage(
|
||||
SCHEMA_VERSION,
|
||||
jobId,
|
||||
TYPE,
|
||||
attachmentId,
|
||||
pipelineVersion,
|
||||
attempt,
|
||||
createdAt
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.vnp.demo.models.Attachment;
|
||||
|
||||
public record AttachmentResponse(
|
||||
UUID id,
|
||||
|
||||
@JsonProperty("chat_id")
|
||||
UUID chatId,
|
||||
|
||||
@JsonProperty("owner_id")
|
||||
UUID ownerId,
|
||||
|
||||
String filename,
|
||||
|
||||
@JsonProperty("content_type")
|
||||
String contentType,
|
||||
|
||||
@JsonProperty("size_bytes")
|
||||
long sizeBytes,
|
||||
|
||||
String sha256,
|
||||
String status,
|
||||
List<Object> variants,
|
||||
|
||||
@JsonProperty("error_code")
|
||||
String errorCode,
|
||||
|
||||
@JsonProperty("created_at")
|
||||
Instant createdAt,
|
||||
|
||||
@JsonProperty("updated_at")
|
||||
Instant updatedAt
|
||||
) {
|
||||
public static AttachmentResponse from(Attachment attachment) {
|
||||
return new AttachmentResponse(
|
||||
attachment.id(),
|
||||
attachment.chatId(),
|
||||
attachment.ownerId(),
|
||||
attachment.filename(),
|
||||
attachment.contentType(),
|
||||
attachment.sizeBytes(),
|
||||
attachment.sha256(),
|
||||
attachment.status(),
|
||||
List.of(),
|
||||
null,
|
||||
attachment.createdAt(),
|
||||
attachment.updatedAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.hibernate.validator.constraints.UniqueElements;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record ChatCreateRequest(
|
||||
@NotBlank
|
||||
@Size(max = 100)
|
||||
String title,
|
||||
|
||||
@NotEmpty
|
||||
@Size(max = 100)
|
||||
@UniqueElements
|
||||
@JsonProperty("member_ids")
|
||||
List<@NotNull UUID> memberIds
|
||||
) {}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record ChatPageResponse(
|
||||
List<ChatResponse> items,
|
||||
@JsonProperty("next_cursor") String nextCursor
|
||||
) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record ChatResponse(
|
||||
UUID id,
|
||||
String title,
|
||||
@JsonProperty("member_ids")
|
||||
List<UUID> memberIds,
|
||||
@JsonProperty("created_at")
|
||||
Instant createdAt
|
||||
) {}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record ErrorResponse(ErrorBody error) {
|
||||
public record ErrorBody(
|
||||
String code,
|
||||
|
||||
String message,
|
||||
|
||||
@JsonProperty("request_id")
|
||||
String requestId
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
public record HealthResponse(String status) {
|
||||
public static HealthResponse ok()
|
||||
{ return new HealthResponse("ok"); }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSetter;
|
||||
import com.fasterxml.jackson.annotation.Nulls;
|
||||
|
||||
public class MessageCreateRequest {
|
||||
|
||||
private String text;
|
||||
private List<UUID> attachmentIds = List.of();
|
||||
|
||||
public MessageCreateRequest() {
|
||||
}
|
||||
|
||||
public MessageCreateRequest(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public MessageCreateRequest(
|
||||
String text,
|
||||
List<UUID> attachmentIds
|
||||
) {
|
||||
this.text = text;
|
||||
this.attachmentIds = attachmentIds;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public String text() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public List<UUID> attachmentIds() {
|
||||
return attachmentIds;
|
||||
}
|
||||
|
||||
@JsonSetter(
|
||||
value = "attachment_ids",
|
||||
nulls = Nulls.FAIL,
|
||||
contentNulls = Nulls.FAIL
|
||||
)
|
||||
public void setAttachmentIds(List<UUID> attachmentIds) {
|
||||
this.attachmentIds = attachmentIds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.vnp.demo.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record MessagePageResponse(
|
||||
List<MessageResponse> items,
|
||||
@JsonProperty("next_cursor") String nextCursor
|
||||
) {}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user